repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/VisualBasic/Portable/Errors/DiagnosticFormatter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The Diagnostic class allows formatting of Visual Basic diagnostics. ''' </summary> Public Class VisualBasicDiagnosticFormatter Inherits DiagnosticFormatter Protected Sub New() End Sub Friend Overrides Function FormatSourceSpan(span As LinePositionSpan, formatter As IFormatProvider) As String Return "(" & (span.Start.Line + 1).ToString() & ") " End Function ''' <summary> ''' Gets the current DiagnosticFormatter instance. ''' </summary> Public Shared Shadows ReadOnly Property Instance As New VisualBasicDiagnosticFormatter() End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The Diagnostic class allows formatting of Visual Basic diagnostics. ''' </summary> Public Class VisualBasicDiagnosticFormatter Inherits DiagnosticFormatter Protected Sub New() End Sub Friend Overrides Function FormatSourceSpan(span As LinePositionSpan, formatter As IFormatProvider) As String Return "(" & (span.Start.Line + 1).ToString() & ") " End Function ''' <summary> ''' Gets the current DiagnosticFormatter instance. ''' </summary> Public Shared Shadows ReadOnly Property Instance As New VisualBasicDiagnosticFormatter() End Class End Namespace
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHandlerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentSemanticTokensFullName)] [ProvidesMethod(Methods.TextDocumentSemanticTokensFullDeltaName)] [ProvidesMethod(Methods.TextDocumentSemanticTokensRangeName)] internal class SemanticTokensHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SemanticTokensHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { var semanticTokensCache = new SemanticTokensCache(); return ImmutableArray.Create<IRequestHandler>( new SemanticTokensHandler(semanticTokensCache), new SemanticTokensEditsHandler(semanticTokensCache), new SemanticTokensRangeHandler(semanticTokensCache)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentSemanticTokensFullName)] [ProvidesMethod(Methods.TextDocumentSemanticTokensFullDeltaName)] [ProvidesMethod(Methods.TextDocumentSemanticTokensRangeName)] internal class SemanticTokensHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SemanticTokensHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { var semanticTokensCache = new SemanticTokensCache(); return ImmutableArray.Create<IRequestHandler>( new SemanticTokensHandler(semanticTokensCache), new SemanticTokensEditsHandler(semanticTokensCache), new SemanticTokensRangeHandler(semanticTokensCache)); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Tools/ExternalAccess/FSharp/Completion/FSharpFileSystemCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal class FSharpFileSystemCompletionHelper { private readonly FileSystemCompletionHelper _fileSystemCompletionHelper; public FSharpFileSystemCompletionHelper( FSharpGlyph folderGlyph, FSharpGlyph fileGlyph, ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, CompletionItemRules itemRules) { _fileSystemCompletionHelper = new FileSystemCompletionHelper( FSharpGlyphHelpers.ConvertTo(folderGlyph), FSharpGlyphHelpers.ConvertTo(fileGlyph), searchPaths, baseDirectoryOpt, allowableExtensions, itemRules); } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) { return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal class FSharpFileSystemCompletionHelper { private readonly FileSystemCompletionHelper _fileSystemCompletionHelper; public FSharpFileSystemCompletionHelper( FSharpGlyph folderGlyph, FSharpGlyph fileGlyph, ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, CompletionItemRules itemRules) { _fileSystemCompletionHelper = new FileSystemCompletionHelper( FSharpGlyphHelpers.ConvertTo(folderGlyph), FSharpGlyphHelpers.ConvertTo(fileGlyph), searchPaths, baseDirectoryOpt, allowableExtensions, itemRules); } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) { return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, cancellationToken); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/VisualBasic/Portable/Binding/SyntheticBoundTrees/SynthesizedPropertyAccessorBase.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.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module SynthesizedPropertyAccessorHelper Friend Function GetBoundMethodBody(accessor As MethodSymbol, backingField As FieldSymbol, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing ' NOTE: Current implementation of this method does generate the code for both getter and setter, ' Ideally it could have been split into two different implementations, but the code gen is ' quite similar in these two cases and current types hierarchy makes this solution preferable Dim propertySymbol = DirectCast(accessor.AssociatedSymbol, PropertySymbol) Dim syntax = DirectCast(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), VisualBasicSyntaxNode) If propertySymbol.Type.IsVoidType Then ' An error is reported elsewhere Return (New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundStatement).Empty, hasErrors:=True)).MakeCompilerGenerated() End If Dim meSymbol As ParameterSymbol = Nothing Dim meReference As BoundExpression = Nothing If Not accessor.IsShared Then meSymbol = accessor.MeParameter meReference = New BoundMeReference(syntax, meSymbol.Type) End If Dim isOverride As Boolean = propertySymbol.IsWithEvents AndAlso propertySymbol.IsOverrides Dim field As FieldSymbol = Nothing Dim fieldAccess As BoundFieldAccess = Nothing Dim myBaseReference As BoundExpression = Nothing Dim baseGet As BoundExpression = Nothing If isOverride Then ' overriding property gets its value via a base call myBaseReference = New BoundMyBaseReference(syntax, meSymbol.Type) Dim baseGetSym = propertySymbol.GetMethod.OverriddenMethod baseGet = New BoundCall( syntax, baseGetSym, Nothing, myBaseReference, ImmutableArray(Of BoundExpression).Empty, Nothing, type:=baseGetSym.ReturnType, suppressObjectClone:=True) Else ' not overriding property operates with field field = backingField fieldAccess = New BoundFieldAccess(syntax, meReference, field, True, field.Type) End If Dim exitLabel = New GeneratedLabelSymbol("exit") Dim statements As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance Dim locals As ImmutableArray(Of LocalSymbol) Dim returnLocal As BoundLocal If accessor.MethodKind = MethodKind.PropertyGet Then ' Declare local variable for function return. Dim local = New SynthesizedLocal(accessor, accessor.ReturnType, SynthesizedLocalKind.LoweringTemp) Dim returnValue As BoundExpression If isOverride Then returnValue = baseGet Else returnValue = fieldAccess.MakeRValue() End If statements.Add(New BoundReturnStatement(syntax, returnValue, local, exitLabel).MakeCompilerGenerated()) locals = ImmutableArray.Create(Of LocalSymbol)(local) returnLocal = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type) Else Debug.Assert(accessor.MethodKind = MethodKind.PropertySet) ' NOTE: at this point number of parameters in a VALID property must be 1. ' In the case when an auto-property has some parameters we assume that ' ERR_AutoPropertyCantHaveParams(36759) is already generated, ' in this case we just ignore all the parameters and assume that the ' last parameter is what we need to use below Debug.Assert(accessor.ParameterCount >= 1) Dim parameter = accessor.Parameters(accessor.ParameterCount - 1) Dim parameterAccess = New BoundParameter(syntax, parameter, isLValue:=False, type:=parameter.Type) Dim eventsToHookup As ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)) = Nothing ' contains temps for handler delegates followed by other stuff that is needed. ' so it will have at least eventsToHookup.Count temps Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing ' accesses to the handler delegates ' we use them once to unhook from old source and then again to hook to the new source Dim handlerlocalAccesses As ArrayBuilder(Of BoundLocal) = Nothing ' //process Handles that need to be hooked up in this method ' //if there are events to hook up, the body will look like this: ' ' Dim tempHandlerLocal = AddressOf handlerMethod ' addressOf is already bound and may contain conversion ' . . . ' Dim tempHandlerLocalN = AddressOf handlerMethodN ' ' Dim valueTemp = [ _backingField | BaseGet ] ' If valueTemp isnot nothing ' ' // unhook handlers from the old value. ' // Note that we can use the handler temps we have just created. ' // Delegate identity is {target, method} so that will work ' ' valueTemp.E1.Remove(tempLocalHandler1) ' valueTemp.E2.Remove(tempLocalHandler2) ' ' End If ' ' //Now store the new value ' ' [ _backingField = value | BaseSet(value) ] ' ' // re-read the value (we use same assignment here as before) ' valueTemp = [ _backingField | BaseGet ] ' ' If valueTemp isnot nothing ' ' // re-hook handlers to the new value. ' ' valueTemp.E1.Add(tempLocalHandler1) ' valueTemp.E2.Add(tempLocalHandler2) ' ' End If ' If propertySymbol.IsWithEvents Then For Each member In accessor.ContainingType.GetMembers() If member.Kind = SymbolKind.Method Then Dim methodMember = DirectCast(member, MethodSymbol) Dim handledEvents = methodMember.HandledEvents ' if method has definition and implementation parts ' their "Handles" should be merged. If methodMember.IsPartial Then Dim implementationPart = methodMember.PartialImplementationPart If implementationPart IsNot Nothing Then handledEvents = handledEvents.Concat(implementationPart.HandledEvents) Else ' partial methods with no implementation do not handle anything Continue For End If End If If Not handledEvents.IsEmpty Then For Each handledEvent In handledEvents If handledEvent.hookupMethod = accessor Then If eventsToHookup Is Nothing Then eventsToHookup = ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)).GetInstance temps = ArrayBuilder(Of LocalSymbol).GetInstance handlerlocalAccesses = ArrayBuilder(Of BoundLocal).GetInstance End If eventsToHookup.Add(New ValueTuple(Of EventSymbol, PropertySymbol)( DirectCast(handledEvent.EventSymbol, EventSymbol), DirectCast(handledEvent.WithEventsSourceProperty, PropertySymbol))) Dim handlerLocal = New SynthesizedLocal(accessor, handledEvent.delegateCreation.Type, SynthesizedLocalKind.LoweringTemp) temps.Add(handlerLocal) Dim localAccess = New BoundLocal(syntax, handlerLocal, handlerLocal.Type) handlerlocalAccesses.Add(localAccess.MakeRValue()) Dim handlerLocalinit = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, localAccess, handledEvent.delegateCreation, False, localAccess.Type)) statements.Add(handlerLocalinit) End If Next End If End If Next End If Dim withEventsLocalAccess As BoundLocal = Nothing Dim withEventsLocalStore As BoundExpressionStatement = Nothing ' need to unhook old handlers before setting a new event source If eventsToHookup IsNot Nothing Then Dim withEventsValue As BoundExpression If isOverride Then withEventsValue = baseGet Else withEventsValue = fieldAccess.MakeRValue() End If Dim withEventsLocal = New SynthesizedLocal(accessor, withEventsValue.Type, SynthesizedLocalKind.LoweringTemp) temps.Add(withEventsLocal) withEventsLocalAccess = New BoundLocal(syntax, withEventsLocal, withEventsLocal.Type) withEventsLocalStore = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, withEventsLocalAccess, withEventsValue, True, withEventsLocal.Type)) statements.Add(withEventsLocalStore) ' if witheventsLocalStore isnot nothing ' ... ' withEventsLocalAccess.eventN_remove(handlerLocalN) ' ... Dim eventRemovals = ArrayBuilder(Of BoundStatement).GetInstance For i As Integer = 0 To eventsToHookup.Count - 1 Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1 ' Normally, we would synthesize lowered bound nodes, but we know that these nodes will ' be run through the LocalRewriter. Let the LocalRewriter handle the special code for ' WinRT events. Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess Dim providerProperty = eventsToHookup(i).Item2 If providerProperty IsNot Nothing Then withEventsProviderAccess = New BoundPropertyAccess(syntax, providerProperty, Nothing, PropertyAccessKind.Get, False, If(providerProperty.IsShared, Nothing, withEventsLocalAccess), ImmutableArray(Of BoundExpression).Empty) End If eventRemovals.Add( New BoundRemoveHandlerStatement( syntax:=syntax, eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type), handler:=handlerlocalAccesses(i))) Next Dim removalStatement = New BoundStatementList(syntax, eventRemovals.ToImmutableAndFree) Dim conditionalRemoval = New BoundIfStatement( syntax, (New BoundBinaryOperator( syntax, BinaryOperatorKind.IsNot, withEventsLocalAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)), False, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated, removalStatement, Nothing) statements.Add(conditionalRemoval.MakeCompilerGenerated) End If ' set the value of the property ' if it is overriding, call the base ' otherwise assign to associated field. Dim valueSettingExpression As BoundExpression If isOverride Then Dim baseSet = accessor.OverriddenMethod valueSettingExpression = New BoundCall( syntax, baseSet, Nothing, myBaseReference, ImmutableArray.Create(Of BoundExpression)(parameterAccess), Nothing, suppressObjectClone:=True, type:=baseSet.ReturnType) Else valueSettingExpression = New BoundAssignmentOperator( syntax, fieldAccess, parameterAccess, suppressObjectClone:=False, type:=propertySymbol.Type) End If statements.Add( (New BoundExpressionStatement( syntax, valueSettingExpression).MakeCompilerGenerated())) ' after setting new event source, hookup handlers If eventsToHookup IsNot Nothing Then statements.Add(withEventsLocalStore) ' if witheventsLocalStore isnot nothing ' ... ' withEventsLocalAccess.eventN_add(handlerLocalN) ' ... Dim eventAdds = ArrayBuilder(Of BoundStatement).GetInstance For i As Integer = 0 To eventsToHookup.Count - 1 Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1 ' Normally, we would synthesize lowered bound nodes, but we know that these nodes will ' be run through the LocalRewriter. Let the LocalRewriter handle the special code for ' WinRT events. Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess Dim providerProperty = eventsToHookup(i).Item2 If providerProperty IsNot Nothing Then withEventsProviderAccess = New BoundPropertyAccess(syntax, providerProperty, Nothing, PropertyAccessKind.Get, False, If(providerProperty.IsShared, Nothing, withEventsLocalAccess), ImmutableArray(Of BoundExpression).Empty) End If eventAdds.Add( New BoundAddHandlerStatement( syntax:=syntax, eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type), handler:=handlerlocalAccesses(i))) Next Dim addStatement = New BoundStatementList(syntax, eventAdds.ToImmutableAndFree()) Dim conditionalAdd = New BoundIfStatement( syntax, (New BoundBinaryOperator( syntax, BinaryOperatorKind.IsNot, withEventsLocalAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)), False, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated, addStatement, Nothing) statements.Add(conditionalAdd.MakeCompilerGenerated) End If locals = If(temps Is Nothing, ImmutableArray(Of LocalSymbol).Empty, temps.ToImmutableAndFree) returnLocal = Nothing If eventsToHookup IsNot Nothing Then eventsToHookup.Free() handlerlocalAccesses.Free() End If End If statements.Add((New BoundLabelStatement(syntax, exitLabel)).MakeCompilerGenerated()) statements.Add((New BoundReturnStatement(syntax, returnLocal, Nothing, Nothing)).MakeCompilerGenerated()) Return (New BoundBlock(syntax, Nothing, locals, statements.ToImmutableAndFree())).MakeCompilerGenerated() End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module SynthesizedPropertyAccessorHelper Friend Function GetBoundMethodBody(accessor As MethodSymbol, backingField As FieldSymbol, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock methodBodyBinder = Nothing ' NOTE: Current implementation of this method does generate the code for both getter and setter, ' Ideally it could have been split into two different implementations, but the code gen is ' quite similar in these two cases and current types hierarchy makes this solution preferable Dim propertySymbol = DirectCast(accessor.AssociatedSymbol, PropertySymbol) Dim syntax = DirectCast(VisualBasic.VisualBasicSyntaxTree.Dummy.GetRoot(), VisualBasicSyntaxNode) If propertySymbol.Type.IsVoidType Then ' An error is reported elsewhere Return (New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundStatement).Empty, hasErrors:=True)).MakeCompilerGenerated() End If Dim meSymbol As ParameterSymbol = Nothing Dim meReference As BoundExpression = Nothing If Not accessor.IsShared Then meSymbol = accessor.MeParameter meReference = New BoundMeReference(syntax, meSymbol.Type) End If Dim isOverride As Boolean = propertySymbol.IsWithEvents AndAlso propertySymbol.IsOverrides Dim field As FieldSymbol = Nothing Dim fieldAccess As BoundFieldAccess = Nothing Dim myBaseReference As BoundExpression = Nothing Dim baseGet As BoundExpression = Nothing If isOverride Then ' overriding property gets its value via a base call myBaseReference = New BoundMyBaseReference(syntax, meSymbol.Type) Dim baseGetSym = propertySymbol.GetMethod.OverriddenMethod baseGet = New BoundCall( syntax, baseGetSym, Nothing, myBaseReference, ImmutableArray(Of BoundExpression).Empty, Nothing, type:=baseGetSym.ReturnType, suppressObjectClone:=True) Else ' not overriding property operates with field field = backingField fieldAccess = New BoundFieldAccess(syntax, meReference, field, True, field.Type) End If Dim exitLabel = New GeneratedLabelSymbol("exit") Dim statements As ArrayBuilder(Of BoundStatement) = ArrayBuilder(Of BoundStatement).GetInstance Dim locals As ImmutableArray(Of LocalSymbol) Dim returnLocal As BoundLocal If accessor.MethodKind = MethodKind.PropertyGet Then ' Declare local variable for function return. Dim local = New SynthesizedLocal(accessor, accessor.ReturnType, SynthesizedLocalKind.LoweringTemp) Dim returnValue As BoundExpression If isOverride Then returnValue = baseGet Else returnValue = fieldAccess.MakeRValue() End If statements.Add(New BoundReturnStatement(syntax, returnValue, local, exitLabel).MakeCompilerGenerated()) locals = ImmutableArray.Create(Of LocalSymbol)(local) returnLocal = New BoundLocal(syntax, local, isLValue:=False, type:=local.Type) Else Debug.Assert(accessor.MethodKind = MethodKind.PropertySet) ' NOTE: at this point number of parameters in a VALID property must be 1. ' In the case when an auto-property has some parameters we assume that ' ERR_AutoPropertyCantHaveParams(36759) is already generated, ' in this case we just ignore all the parameters and assume that the ' last parameter is what we need to use below Debug.Assert(accessor.ParameterCount >= 1) Dim parameter = accessor.Parameters(accessor.ParameterCount - 1) Dim parameterAccess = New BoundParameter(syntax, parameter, isLValue:=False, type:=parameter.Type) Dim eventsToHookup As ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)) = Nothing ' contains temps for handler delegates followed by other stuff that is needed. ' so it will have at least eventsToHookup.Count temps Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing ' accesses to the handler delegates ' we use them once to unhook from old source and then again to hook to the new source Dim handlerlocalAccesses As ArrayBuilder(Of BoundLocal) = Nothing ' //process Handles that need to be hooked up in this method ' //if there are events to hook up, the body will look like this: ' ' Dim tempHandlerLocal = AddressOf handlerMethod ' addressOf is already bound and may contain conversion ' . . . ' Dim tempHandlerLocalN = AddressOf handlerMethodN ' ' Dim valueTemp = [ _backingField | BaseGet ] ' If valueTemp isnot nothing ' ' // unhook handlers from the old value. ' // Note that we can use the handler temps we have just created. ' // Delegate identity is {target, method} so that will work ' ' valueTemp.E1.Remove(tempLocalHandler1) ' valueTemp.E2.Remove(tempLocalHandler2) ' ' End If ' ' //Now store the new value ' ' [ _backingField = value | BaseSet(value) ] ' ' // re-read the value (we use same assignment here as before) ' valueTemp = [ _backingField | BaseGet ] ' ' If valueTemp isnot nothing ' ' // re-hook handlers to the new value. ' ' valueTemp.E1.Add(tempLocalHandler1) ' valueTemp.E2.Add(tempLocalHandler2) ' ' End If ' If propertySymbol.IsWithEvents Then For Each member In accessor.ContainingType.GetMembers() If member.Kind = SymbolKind.Method Then Dim methodMember = DirectCast(member, MethodSymbol) Dim handledEvents = methodMember.HandledEvents ' if method has definition and implementation parts ' their "Handles" should be merged. If methodMember.IsPartial Then Dim implementationPart = methodMember.PartialImplementationPart If implementationPart IsNot Nothing Then handledEvents = handledEvents.Concat(implementationPart.HandledEvents) Else ' partial methods with no implementation do not handle anything Continue For End If End If If Not handledEvents.IsEmpty Then For Each handledEvent In handledEvents If handledEvent.hookupMethod = accessor Then If eventsToHookup Is Nothing Then eventsToHookup = ArrayBuilder(Of ValueTuple(Of EventSymbol, PropertySymbol)).GetInstance temps = ArrayBuilder(Of LocalSymbol).GetInstance handlerlocalAccesses = ArrayBuilder(Of BoundLocal).GetInstance End If eventsToHookup.Add(New ValueTuple(Of EventSymbol, PropertySymbol)( DirectCast(handledEvent.EventSymbol, EventSymbol), DirectCast(handledEvent.WithEventsSourceProperty, PropertySymbol))) Dim handlerLocal = New SynthesizedLocal(accessor, handledEvent.delegateCreation.Type, SynthesizedLocalKind.LoweringTemp) temps.Add(handlerLocal) Dim localAccess = New BoundLocal(syntax, handlerLocal, handlerLocal.Type) handlerlocalAccesses.Add(localAccess.MakeRValue()) Dim handlerLocalinit = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, localAccess, handledEvent.delegateCreation, False, localAccess.Type)) statements.Add(handlerLocalinit) End If Next End If End If Next End If Dim withEventsLocalAccess As BoundLocal = Nothing Dim withEventsLocalStore As BoundExpressionStatement = Nothing ' need to unhook old handlers before setting a new event source If eventsToHookup IsNot Nothing Then Dim withEventsValue As BoundExpression If isOverride Then withEventsValue = baseGet Else withEventsValue = fieldAccess.MakeRValue() End If Dim withEventsLocal = New SynthesizedLocal(accessor, withEventsValue.Type, SynthesizedLocalKind.LoweringTemp) temps.Add(withEventsLocal) withEventsLocalAccess = New BoundLocal(syntax, withEventsLocal, withEventsLocal.Type) withEventsLocalStore = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, withEventsLocalAccess, withEventsValue, True, withEventsLocal.Type)) statements.Add(withEventsLocalStore) ' if witheventsLocalStore isnot nothing ' ... ' withEventsLocalAccess.eventN_remove(handlerLocalN) ' ... Dim eventRemovals = ArrayBuilder(Of BoundStatement).GetInstance For i As Integer = 0 To eventsToHookup.Count - 1 Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1 ' Normally, we would synthesize lowered bound nodes, but we know that these nodes will ' be run through the LocalRewriter. Let the LocalRewriter handle the special code for ' WinRT events. Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess Dim providerProperty = eventsToHookup(i).Item2 If providerProperty IsNot Nothing Then withEventsProviderAccess = New BoundPropertyAccess(syntax, providerProperty, Nothing, PropertyAccessKind.Get, False, If(providerProperty.IsShared, Nothing, withEventsLocalAccess), ImmutableArray(Of BoundExpression).Empty) End If eventRemovals.Add( New BoundRemoveHandlerStatement( syntax:=syntax, eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type), handler:=handlerlocalAccesses(i))) Next Dim removalStatement = New BoundStatementList(syntax, eventRemovals.ToImmutableAndFree) Dim conditionalRemoval = New BoundIfStatement( syntax, (New BoundBinaryOperator( syntax, BinaryOperatorKind.IsNot, withEventsLocalAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)), False, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated, removalStatement, Nothing) statements.Add(conditionalRemoval.MakeCompilerGenerated) End If ' set the value of the property ' if it is overriding, call the base ' otherwise assign to associated field. Dim valueSettingExpression As BoundExpression If isOverride Then Dim baseSet = accessor.OverriddenMethod valueSettingExpression = New BoundCall( syntax, baseSet, Nothing, myBaseReference, ImmutableArray.Create(Of BoundExpression)(parameterAccess), Nothing, suppressObjectClone:=True, type:=baseSet.ReturnType) Else valueSettingExpression = New BoundAssignmentOperator( syntax, fieldAccess, parameterAccess, suppressObjectClone:=False, type:=propertySymbol.Type) End If statements.Add( (New BoundExpressionStatement( syntax, valueSettingExpression).MakeCompilerGenerated())) ' after setting new event source, hookup handlers If eventsToHookup IsNot Nothing Then statements.Add(withEventsLocalStore) ' if witheventsLocalStore isnot nothing ' ... ' withEventsLocalAccess.eventN_add(handlerLocalN) ' ... Dim eventAdds = ArrayBuilder(Of BoundStatement).GetInstance For i As Integer = 0 To eventsToHookup.Count - 1 Dim eventSymbol As EventSymbol = eventsToHookup(i).Item1 ' Normally, we would synthesize lowered bound nodes, but we know that these nodes will ' be run through the LocalRewriter. Let the LocalRewriter handle the special code for ' WinRT events. Dim withEventsProviderAccess As BoundExpression = withEventsLocalAccess Dim providerProperty = eventsToHookup(i).Item2 If providerProperty IsNot Nothing Then withEventsProviderAccess = New BoundPropertyAccess(syntax, providerProperty, Nothing, PropertyAccessKind.Get, False, If(providerProperty.IsShared, Nothing, withEventsLocalAccess), ImmutableArray(Of BoundExpression).Empty) End If eventAdds.Add( New BoundAddHandlerStatement( syntax:=syntax, eventAccess:=New BoundEventAccess(syntax, withEventsProviderAccess, eventSymbol, eventSymbol.Type), handler:=handlerlocalAccesses(i))) Next Dim addStatement = New BoundStatementList(syntax, eventAdds.ToImmutableAndFree()) Dim conditionalAdd = New BoundIfStatement( syntax, (New BoundBinaryOperator( syntax, BinaryOperatorKind.IsNot, withEventsLocalAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Object)), False, accessor.ContainingAssembly.GetSpecialType(SpecialType.System_Boolean))).MakeCompilerGenerated, addStatement, Nothing) statements.Add(conditionalAdd.MakeCompilerGenerated) End If locals = If(temps Is Nothing, ImmutableArray(Of LocalSymbol).Empty, temps.ToImmutableAndFree) returnLocal = Nothing If eventsToHookup IsNot Nothing Then eventsToHookup.Free() handlerlocalAccesses.Free() End If End If statements.Add((New BoundLabelStatement(syntax, exitLabel)).MakeCompilerGenerated()) statements.Add((New BoundReturnStatement(syntax, returnLocal, Nothing, Nothing)).MakeCompilerGenerated()) Return (New BoundBlock(syntax, Nothing, locals, statements.ToImmutableAndFree())).MakeCompilerGenerated() End Function End Module End Namespace
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/Parameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal class Parameter : IParameter { private readonly SignatureHelpParameter _parameter; private string _documentation; private readonly int _contentLength; private readonly int _index; private readonly int _prettyPrintedIndex; public string Documentation => _documentation ?? (_documentation = _parameter.DocumentationFactory(CancellationToken.None).GetFullText()); public string Name => _parameter.Name; public Span Locus => new(_index, _contentLength); public Span PrettyPrintedLocus => new(_prettyPrintedIndex, _contentLength); public ISignature Signature { get; } public Parameter( Signature signature, SignatureHelpParameter parameter, string content, int index, int prettyPrintedIndex) { _parameter = parameter; this.Signature = signature; _contentLength = content.Length; _index = index; _prettyPrintedIndex = prettyPrintedIndex; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal class Parameter : IParameter { private readonly SignatureHelpParameter _parameter; private string _documentation; private readonly int _contentLength; private readonly int _index; private readonly int _prettyPrintedIndex; public string Documentation => _documentation ?? (_documentation = _parameter.DocumentationFactory(CancellationToken.None).GetFullText()); public string Name => _parameter.Name; public Span Locus => new(_index, _contentLength); public Span PrettyPrintedLocus => new(_prettyPrintedIndex, _contentLength); public ISignature Signature { get; } public Parameter( Signature signature, SignatureHelpParameter parameter, string content, int index, int prettyPrintedIndex) { _parameter = parameter; this.Signature = signature; _contentLength = content.Length; _index = index; _prettyPrintedIndex = prettyPrintedIndex; } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Workspaces/Core/Portable/Editing/SymbolEditor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to symbol source declarations. /// </summary> public sealed class SymbolEditor { private readonly Solution _originalSolution; private Solution _currentSolution; private SymbolEditor(Solution solution) { _originalSolution = solution; _currentSolution = solution; } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Solution solution) { if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return new SymbolEditor(solution); } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return new SymbolEditor(document.Project.Solution); } /// <summary> /// The original solution. /// </summary> public Solution OriginalSolution => _originalSolution; /// <summary> /// The solution with the edits applied. /// </summary> public Solution ChangedSolution => _currentSolution; /// <summary> /// The documents changed since the <see cref="SymbolEditor"/> was constructed. /// </summary> public IEnumerable<Document> GetChangedDocuments() { var solutionChanges = _currentSolution.GetChanges(_originalSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var id in projectChanges.GetAddedDocuments()) { yield return _currentSolution.GetDocument(id); } foreach (var id in projectChanges.GetChangedDocuments()) { yield return _currentSolution.GetDocument(id); } } foreach (var project in solutionChanges.GetAddedProjects()) { foreach (var id in project.DocumentIds) { yield return project.GetDocument(id); } } } /// <summary> /// Gets the current symbol for a source symbol. /// </summary> public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default) { var symbolId = DocumentationCommentId.CreateDeclarationId(symbol); // check to see if symbol is from current solution var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // check to see if it is from original solution project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // try to find symbol from any project (from current solution) with matching assembly name foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly)) { var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false); if (currentSymbol != null) { return currentSymbol; } } return null; } private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap; private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly) { if (_assemblyNameToProjectIdMap == null) { _assemblyNameToProjectIdMap = _originalSolution.Projects .ToLookup(p => p.AssemblyName, p => p.Id) .ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g)); } if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out var projectIds)) { projectIds = ImmutableArray<ProjectId>.Empty; } return projectIds; } private static async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken) { var project = solution.GetProject(projectId); if (project.SupportsCompilation) { var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList(); if (symbols.Count == 1) { return symbols[0]; } else if (symbols.Count > 1) { #if false // if we have multiple matches, use the same index that it appeared as in the original solution. var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList(); var index = originalSymbols.IndexOf(originalSymbol); if (index >= 0 && index <= symbols.Count) { return symbols[index]; } #else return symbols[0]; #endif } } return null; } /// <summary> /// Gets the current declarations for the specified symbol. /// </summary> public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); return this.GetDeclarations(currentSymbol).ToBoxedImmutableArray(); } /// <summary> /// Gets the declaration syntax nodes for a given symbol. /// </summary> private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol) { return symbol.DeclaringSyntaxReferences .Select(sr => sr.GetSyntax()) .Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n)) .Where(d => d != null); } /// <summary> /// Gets the best declaration node for adding members. /// </summary> private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration) { declaration = GetDeclarations(symbol).FirstOrDefault(); return declaration != null; } /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <returns></returns> public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration); /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns></returns> public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken); /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); if (TryGetBestDeclarationForSingleEdit(currentSymbol, out var declaration)) { return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } return null; } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } private static void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol) { if (currentSymbol == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name)); } } private async Task<ISymbol> EditDeclarationAsync( ISymbol currentSymbol, SyntaxNode declaration, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken) { var doc = _currentSolution.GetDocument(declaration.SyntaxTree); var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false); editor.TrackNode(declaration); await editAction(editor, declaration, cancellationToken).ConfigureAwait(false); var newDoc = editor.GetChangedDocument(); _currentSolution = newDoc.Project.Solution; // try to find new symbol by looking up via original declaration var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } // otherwise fallback to rebinding with original symbol return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var sourceTree = location.SourceTree; var doc = _currentSolution.GetDocument(sourceTree) ?? _originalSolution.GetDocument(sourceTree); if (doc != null) { return EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken); } throw new ArgumentException("The location specified is not part of the solution.", nameof(location)); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, location, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } private async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DocumentId documentId, int position, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d => { var doc = _currentSolution.GetDocument(d.SyntaxTree); return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position); }); if (decl == null) { throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position)); } return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentMember, member); // get first symbol declaration that encompasses at least one of the member declarations var memberDecls = this.GetDeclarations(currentMember).ToList(); var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan))); if (declaration == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name)); } return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, member, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id); var solutionEditor = new SolutionEditor(_currentSolution); foreach (var declGroup in declsByDocId) { var docId = declGroup.Key; var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { editor.TrackNode(decl); // ensure the declaration gets tracked await editAction(editor, decl, cancellationToken).ConfigureAwait(false); } } _currentSolution = solutionEditor.GetChangedSolution(); // try to find new symbol by looking up via original declarations foreach (var declGroup in declsByDocId) { var doc = _currentSolution.GetDocument(declGroup.Key); var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } } } // otherwise fallback to rebinding with original symbol return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditAllDeclarationsAsync( symbol, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to symbol source declarations. /// </summary> public sealed class SymbolEditor { private readonly Solution _originalSolution; private Solution _currentSolution; private SymbolEditor(Solution solution) { _originalSolution = solution; _currentSolution = solution; } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Solution solution) { if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return new SymbolEditor(solution); } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return new SymbolEditor(document.Project.Solution); } /// <summary> /// The original solution. /// </summary> public Solution OriginalSolution => _originalSolution; /// <summary> /// The solution with the edits applied. /// </summary> public Solution ChangedSolution => _currentSolution; /// <summary> /// The documents changed since the <see cref="SymbolEditor"/> was constructed. /// </summary> public IEnumerable<Document> GetChangedDocuments() { var solutionChanges = _currentSolution.GetChanges(_originalSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var id in projectChanges.GetAddedDocuments()) { yield return _currentSolution.GetDocument(id); } foreach (var id in projectChanges.GetChangedDocuments()) { yield return _currentSolution.GetDocument(id); } } foreach (var project in solutionChanges.GetAddedProjects()) { foreach (var id in project.DocumentIds) { yield return project.GetDocument(id); } } } /// <summary> /// Gets the current symbol for a source symbol. /// </summary> public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default) { var symbolId = DocumentationCommentId.CreateDeclarationId(symbol); // check to see if symbol is from current solution var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // check to see if it is from original solution project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // try to find symbol from any project (from current solution) with matching assembly name foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly)) { var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false); if (currentSymbol != null) { return currentSymbol; } } return null; } private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap; private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly) { if (_assemblyNameToProjectIdMap == null) { _assemblyNameToProjectIdMap = _originalSolution.Projects .ToLookup(p => p.AssemblyName, p => p.Id) .ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g)); } if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out var projectIds)) { projectIds = ImmutableArray<ProjectId>.Empty; } return projectIds; } private static async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken) { var project = solution.GetProject(projectId); if (project.SupportsCompilation) { var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList(); if (symbols.Count == 1) { return symbols[0]; } else if (symbols.Count > 1) { #if false // if we have multiple matches, use the same index that it appeared as in the original solution. var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList(); var index = originalSymbols.IndexOf(originalSymbol); if (index >= 0 && index <= symbols.Count) { return symbols[index]; } #else return symbols[0]; #endif } } return null; } /// <summary> /// Gets the current declarations for the specified symbol. /// </summary> public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); return this.GetDeclarations(currentSymbol).ToBoxedImmutableArray(); } /// <summary> /// Gets the declaration syntax nodes for a given symbol. /// </summary> private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol) { return symbol.DeclaringSyntaxReferences .Select(sr => sr.GetSyntax()) .Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n)) .Where(d => d != null); } /// <summary> /// Gets the best declaration node for adding members. /// </summary> private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration) { declaration = GetDeclarations(symbol).FirstOrDefault(); return declaration != null; } /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <returns></returns> public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration); /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns></returns> public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken); /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); if (TryGetBestDeclarationForSingleEdit(currentSymbol, out var declaration)) { return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } return null; } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } private static void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol) { if (currentSymbol == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name)); } } private async Task<ISymbol> EditDeclarationAsync( ISymbol currentSymbol, SyntaxNode declaration, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken) { var doc = _currentSolution.GetDocument(declaration.SyntaxTree); var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false); editor.TrackNode(declaration); await editAction(editor, declaration, cancellationToken).ConfigureAwait(false); var newDoc = editor.GetChangedDocument(); _currentSolution = newDoc.Project.Solution; // try to find new symbol by looking up via original declaration var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } // otherwise fallback to rebinding with original symbol return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var sourceTree = location.SourceTree; var doc = _currentSolution.GetDocument(sourceTree) ?? _originalSolution.GetDocument(sourceTree); if (doc != null) { return EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken); } throw new ArgumentException("The location specified is not part of the solution.", nameof(location)); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, location, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } private async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DocumentId documentId, int position, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d => { var doc = _currentSolution.GetDocument(d.SyntaxTree); return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position); }); if (decl == null) { throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position)); } return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentMember, member); // get first symbol declaration that encompasses at least one of the member declarations var memberDecls = this.GetDeclarations(currentMember).ToList(); var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan))); if (declaration == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name)); } return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditOneDeclarationAsync( symbol, member, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id); var solutionEditor = new SolutionEditor(_currentSolution); foreach (var declGroup in declsByDocId) { var docId = declGroup.Key; var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { editor.TrackNode(decl); // ensure the declaration gets tracked await editAction(editor, decl, cancellationToken).ConfigureAwait(false); } } _currentSolution = solutionEditor.GetChangedSolution(); // try to find new symbol by looking up via original declarations foreach (var declGroup in declsByDocId) { var doc = _currentSolution.GetDocument(declGroup.Key); var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } } } // otherwise fallback to rebinding with original symbol return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default) { return this.EditAllDeclarationsAsync( symbol, (e, d, c) => { editAction(e, d); return Task.CompletedTask; }, cancellationToken); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/BasicExpressionCompilerTest.Debug.xunit
<?xml version="1.0" encoding="utf-8"?> <xunit> <assemblies> <assembly filename="..\..\..\..\..\Binaries\Debug\Roslyn.ExpressionEvaluator.VisualBasic.ExpressionCompiler.UnitTests.dll" shadow-copy="false" /> </assemblies> </xunit>
<?xml version="1.0" encoding="utf-8"?> <xunit> <assemblies> <assembly filename="..\..\..\..\..\Binaries\Debug\Roslyn.ExpressionEvaluator.VisualBasic.ExpressionCompiler.UnitTests.dll" shadow-copy="false" /> </assemblies> </xunit>
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayGlobalNamespaceStyle.cs
// Licensed to the .NET Foundation under one or more 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> /// Specifies the options for how to display the global namespace in the description of a symbol. /// </summary> /// <remarks> /// Any of these styles may be overridden by <see cref="SymbolDisplayTypeQualificationStyle"/>. /// </remarks> public enum SymbolDisplayGlobalNamespaceStyle { /// <summary> /// Omits the global namespace, unconditionally. /// </summary> Omitted = 0, /// <summary> /// Omits the global namespace if it is being displayed as a containing symbol (i.e. not on its own). /// </summary> OmittedAsContaining = 1, /// <summary> /// Include the global namespace, unconditionally. /// </summary> Included = 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. namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how to display the global namespace in the description of a symbol. /// </summary> /// <remarks> /// Any of these styles may be overridden by <see cref="SymbolDisplayTypeQualificationStyle"/>. /// </remarks> public enum SymbolDisplayGlobalNamespaceStyle { /// <summary> /// Omits the global namespace, unconditionally. /// </summary> Omitted = 0, /// <summary> /// Omits the global namespace if it is being displayed as a containing symbol (i.e. not on its own). /// </summary> OmittedAsContaining = 1, /// <summary> /// Include the global namespace, unconditionally. /// </summary> Included = 2, } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineStates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp { internal static class StateMachineStates { internal const int FinishedStateMachine = -2; internal const int NotStartedStateMachine = -1; internal const int FirstUnusedState = 0; // used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case internal const int InitialAsyncIteratorStateMachine = -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. #nullable disable namespace Microsoft.CodeAnalysis.CSharp { internal static class StateMachineStates { internal const int FinishedStateMachine = -2; internal const int NotStartedStateMachine = -1; internal const int FirstUnusedState = 0; // used for async-iterators to distinguish initial state from running state (-1) so that DisposeAsync can throw in latter case internal const int InitialAsyncIteratorStateMachine = -3; } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">プロジェクトのビルド</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">インタラクティブ ウィンドウに選択内容をコピーしています。</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">名前変更の実行でエラーが発生しました: '{0}'</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">インタラクティブ ウィンドウで選択を実行します。</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">対話型ホスト プロセス プラットフォーム</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">参照アセンブリの一覧を印刷します。</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">実行環境を初期状態にリセットし、履歴を保持します。</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">クリーンな環境 (mscorlib のみを参照) にリセットし、初期化スクリプトは実行しません。</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">対話をリセットしています</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">実行エンジンをリセットしています。</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">CurrentWindow プロパティは 1 回のみ割り当てることができます。</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">このインタラクティブ ウィンドウの実装で、参照コマンドはサポートされていません。</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">プロジェクトのビルド</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">インタラクティブ ウィンドウに選択内容をコピーしています。</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">名前変更の実行でエラーが発生しました: '{0}'</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">インタラクティブ ウィンドウで選択を実行します。</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">対話型ホスト プロセス プラットフォーム</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">参照アセンブリの一覧を印刷します。</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">実行環境を初期状態にリセットし、履歴を保持します。</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">クリーンな環境 (mscorlib のみを参照) にリセットし、初期化スクリプトは実行しません。</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">対話をリセットしています</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">実行エンジンをリセットしています。</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">CurrentWindow プロパティは 1 回のみ割り当てることができます。</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">このインタラクティブ ウィンドウの実装で、参照コマンドはサポートされていません。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/Test/Resources/Core/SymbolsTests/MDTestLib1.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL!L! ^' @@ @'S@`  H.textd  `.rsrc@ @@.reloc `@B@'H 0( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *BSJB v4.0.30319l#~\`#Strings#US#GUID\#BlobG %3N%$&*18?FMT [ ` g n s x}P  p  x                      X  `    h  HHL $ 4 L - .+2.3;   $  C     ((*,..HHL<Module>mscorlibC1`1TC2`2TC3`1TC4`2C100`1C101`1C102`1C103`1C104`1C105`1C106`1C107C201`1C202`1C203C204I101I102C2`1C3C108`1C4`1C1_TSystemObject.ctorTC2_T1TC2_T2TC3_T1TC4_T1TC4_T2TC2_TC108_TC4_TSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMDTestLib1MDTestLib1.dll 7HR/iz\V4 PT\ TWrapNonExceptionThrows0'N' @'_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMDTestLib1.dll(LegalCopyright HOriginalFilenameMDTestLib1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 `7
MZ@ !L!This program cannot be run in DOS mode. $PEL!L! ^' @@ @'S@`  H.textd  `.rsrc@ @@.reloc `@B@'H 0( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *( *BSJB v4.0.30319l#~\`#Strings#US#GUID\#BlobG %3N%$&*18?FMT [ ` g n s x}P  p  x                      X  `    h  HHL $ 4 L - .+2.3;   $  C     ((*,..HHL<Module>mscorlibC1`1TC2`2TC3`1TC4`2C100`1C101`1C102`1C103`1C104`1C105`1C106`1C107C201`1C202`1C203C204I101I102C2`1C3C108`1C4`1C1_TSystemObject.ctorTC2_T1TC2_T2TC3_T1TC4_T1TC4_T2TC2_TC108_TC4_TSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMDTestLib1MDTestLib1.dll 7HR/iz\V4 PT\ TWrapNonExceptionThrows0'N' @'_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMDTestLib1.dll(LegalCopyright HOriginalFilenameMDTestLib1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 `7
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/CSharp/Test/CommandLine/SarifErrorLoggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class SarifErrorLoggerTests : CommandLineTestBase { protected abstract string ErrorLogQualifier { get; } internal abstract string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd); internal abstract string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification); protected void NoDiagnosticsImpl() { var helloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; var hello = Temp.CreateFile().WriteAllText(helloWorldCS).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", hello, $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString().Trim()); Assert.Equal(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForNoDiagnostics(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(hello); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsImpl() { var source = @" public class C { private int x; }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsSuppressedImpl() { var source = @" public class C { #pragma warning disable CS0169 private int x; #pragma warning restore CS0169 }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsWithAndWithoutLocationImpl() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); string[] arguments = new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = ""Justification1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = ""Justification2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, "Justification1"); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = """")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = """")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, ""); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithNullJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = null)] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = null)] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class SarifErrorLoggerTests : CommandLineTestBase { protected abstract string ErrorLogQualifier { get; } internal abstract string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd); internal abstract string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification); protected void NoDiagnosticsImpl() { var helloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; var hello = Temp.CreateFile().WriteAllText(helloWorldCS).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", hello, $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString().Trim()); Assert.Equal(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForNoDiagnostics(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(hello); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsImpl() { var source = @" public class C { private int x; }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsSuppressedImpl() { var source = @" public class C { #pragma warning disable CS0169 private int x; #pragma warning restore CS0169 }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsWithAndWithoutLocationImpl() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); string[] arguments = new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = ""Justification1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = ""Justification2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, "Justification1"); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = """")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = """")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, ""); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithNullJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = null)] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = null)] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Workspaces/Core/Portable/Shared/Extensions/SafeHandleExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SafeHandleExtensions { /// <summary> /// Acquires a lease on a safe handle. The lease increments the reference count of the <see cref="SafeHandle"/> /// to ensure the handle is not released prior to the lease being released. /// </summary> /// <remarks> /// This method is intended to be used in the initializer of a <c>using</c> statement. Failing to release the /// lease will permanently prevent the underlying <see cref="SafeHandle"/> from being released by the garbage /// collector. /// </remarks> /// <param name="handle">The <see cref="SafeHandle"/> to lease.</param> /// <returns>A <see cref="SafeHandleLease"/>, which must be disposed to release the resource.</returns> /// <exception cref="ObjectDisposedException">If the lease could not be acquired.</exception> public static SafeHandleLease Lease(this SafeHandle handle) { RoslynDebug.AssertNotNull(handle); var success = false; try { handle.DangerousAddRef(ref success); Debug.Assert(success, $"{nameof(SafeHandle.DangerousAddRef)} does not return when {nameof(success)} is false."); return new SafeHandleLease(handle); } catch { if (success) handle.DangerousRelease(); 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 System.Diagnostics; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SafeHandleExtensions { /// <summary> /// Acquires a lease on a safe handle. The lease increments the reference count of the <see cref="SafeHandle"/> /// to ensure the handle is not released prior to the lease being released. /// </summary> /// <remarks> /// This method is intended to be used in the initializer of a <c>using</c> statement. Failing to release the /// lease will permanently prevent the underlying <see cref="SafeHandle"/> from being released by the garbage /// collector. /// </remarks> /// <param name="handle">The <see cref="SafeHandle"/> to lease.</param> /// <returns>A <see cref="SafeHandleLease"/>, which must be disposed to release the resource.</returns> /// <exception cref="ObjectDisposedException">If the lease could not be acquired.</exception> public static SafeHandleLease Lease(this SafeHandle handle) { RoslynDebug.AssertNotNull(handle); var success = false; try { handle.DangerousAddRef(ref success); Debug.Assert(success, $"{nameof(SafeHandle.DangerousAddRef)} does not return when {nameof(success)} is false."); return new SafeHandleLease(handle); } catch { if (success) handle.DangerousRelease(); throw; } } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/VisualStudio/Core/Def/Implementation/KeybindingReset/ReSharperStatus.cs
// Licensed to the .NET Foundation under one or more 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.KeybindingReset { internal enum ReSharperStatus { /// <summary> /// Disabled in the extension manager or not installed. /// </summary> NotInstalledOrDisabled, /// <summary> /// ReSharper is suspended. Package is loaded, but is not actually performing actions. /// </summary> Suspended, /// <summary> /// ReSharper is installed and enabled. /// </summary> Enabled } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.KeybindingReset { internal enum ReSharperStatus { /// <summary> /// Disabled in the extension manager or not installed. /// </summary> NotInstalledOrDisabled, /// <summary> /// ReSharper is suspended. Package is loaded, but is not actually performing actions. /// </summary> Suspended, /// <summary> /// ReSharper is installed and enabled. /// </summary> Enabled } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/LocationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Tools/BuildBoss/SolutionUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal static class SolutionUtil { internal static List<ProjectEntry> ParseProjects(string solutionPath) { using (var reader = new StreamReader(solutionPath)) { var list = new List<ProjectEntry>(); while (true) { var line = reader.ReadLine(); if (line == null) { break; } if (!line.StartsWith("Project")) { continue; } list.Add(ParseProjectLine(line)); } return list; } } private static ProjectEntry ParseProjectLine(string line) { var index = 0; var typeGuid = ParseStringLiteral(line, ref index); var name = ParseStringLiteral(line, ref index); var filePath = ParseStringLiteral(line, ref index); var guid = ParseStringLiteral(line, ref index); return new ProjectEntry( relativeFilePath: filePath, name: name, projectGuid: Guid.Parse(guid), typeGuid: Guid.Parse(typeGuid)); } private static string ParseStringLiteral(string line, ref int index) { var start = line.IndexOf('"', index); if (start < 0) { goto error; } start++; var end = line.IndexOf('"', start); if (end < 0) { goto error; } index = end + 1; return line.Substring(start, end - start); error: throw new Exception($"Invalid project line {line}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal static class SolutionUtil { internal static List<ProjectEntry> ParseProjects(string solutionPath) { using (var reader = new StreamReader(solutionPath)) { var list = new List<ProjectEntry>(); while (true) { var line = reader.ReadLine(); if (line == null) { break; } if (!line.StartsWith("Project")) { continue; } list.Add(ParseProjectLine(line)); } return list; } } private static ProjectEntry ParseProjectLine(string line) { var index = 0; var typeGuid = ParseStringLiteral(line, ref index); var name = ParseStringLiteral(line, ref index); var filePath = ParseStringLiteral(line, ref index); var guid = ParseStringLiteral(line, ref index); return new ProjectEntry( relativeFilePath: filePath, name: name, projectGuid: Guid.Parse(guid), typeGuid: Guid.Parse(typeGuid)); } private static string ParseStringLiteral(string line, ref int index) { var start = line.IndexOf('"', index); if (start < 0) { goto error; } start++; var end = line.IndexOf('"', start); if (end < 0) { goto error; } index = end + 1; return line.Substring(start, end - start); error: throw new Exception($"Invalid project line {line}"); } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/PseudoVariableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class PseudoVariableTests : ExpressionCompilerTestBase { [Fact] public void UnrecognizedVariable() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$v", out error); Assert.Equal("error CS0103: The name '$v' does not exist in the current context", error); }); } [Fact] public void GlobalName() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "global::$exception", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0400: The type or namespace name '$exception' could not be found in the global namespace (are you missing an assembly reference?)", error); } [Fact] public void QualifiedName() { var source = @"class C { void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "this.$exception", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'C' does not contain a definition for '$exception' and no accessible extension method '$exception' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)", error); }); } /// <summary> /// Generate call to intrinsic method for $exception, /// $stowedexception. /// </summary> [Fact] public void Exception() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(System.IO.IOException)), ExceptionAlias(typeof(InvalidOperationException), stowed: true)); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "(System.Exception)$exception ?? $stowedexception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""System.IO.IOException"" IL_000a: dup IL_000b: brtrue.s IL_0018 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetStowedException()"" IL_0013: castclass ""System.InvalidOperationException"" IL_0018: ret }"); }); } [Fact] public void ReturnValue() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(object)), ReturnValueAlias(2, typeof(string))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue ?? $ReturnValue2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: dup IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldc.i4.2 IL_000b: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0010: castclass ""string"" IL_0015: ret }"); // Value type $ReturnValue. context = CreateMethodContext( runtime, "C.M"); aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(int?))); testData = new CompilationTestData(); result = context.CompileExpression( "((int?)$ReturnValue).HasValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int? V_0) IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int?"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""bool int?.HasValue.get"" IL_0013: ret }"); }); } /// <summary> /// Negative index should be treated as separate tokens. /// </summary> [Fact] public void ReturnValueNegative() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "(int)$ReturnValue-2", out error, ReturnValueAlias()); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: ret }"); }); } /// <summary> /// Dev12 syntax "[0-9]+#" not supported. /// </summary> [WorkItem(1071347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1071347")] [Fact] public void ObjectId_EarlierSyntax() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; context.CompileExpression( "23#", out error); Assert.Equal("error CS2043: 'id#' syntax is no longer supported. Use '$id' instead.", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ObjectId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( ObjectIdAlias(23, typeof(string)), ObjectIdAlias(4, typeof(Type))); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$23 ?? $4.BaseType", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 2 IL_0000: ldstr ""$23"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""string"" IL_000f: dup IL_0010: brtrue.s IL_0027 IL_0012: pop IL_0013: ldstr ""$4"" IL_0018: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_001d: castclass ""System.Type"" IL_0022: callvirt ""System.Type System.Type.BaseType.get"" IL_0027: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1101017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101017")] public void NestedGenericValueType() { var source = @"class C { internal struct S<T> { internal T F; } static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "C+S`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "s.F + 1", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, null, // preferredUICulture testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""C.S<int>"" IL_000f: ldfld ""int C.S<int>.F"" IL_0014: ldc.i4.1 IL_0015: add IL_0016: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ArrayType() { var source = @"class C { object F; static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("a", "C[]"), VariableAlias("b", "System.Int32[,], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "a[b[1, 0]].F", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 4 IL_0000: ldstr ""a"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""C[]"" IL_000f: ldstr ""b"" IL_0014: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0019: castclass ""int[,]"" IL_001e: ldc.i4.1 IL_001f: ldc.i4.0 IL_0020: call ""int[*,*].Get"" IL_0025: ldelem.ref IL_0026: ldfld ""object C.F"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type name may be from an /// unrecognized assembly. For instance, if the type was /// defined in a previous evaluation, say an anonymous /// type (e.g.: evaluate "o" after "var o = new { P = 1 };"). /// </summary> [Fact] public void UnrecognizedAssembly() { var source = @"struct S<T> { internal T F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { string error; var testData = new CompilationTestData(); // Unrecognized type. var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("o", "T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "o.P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized array element type. aliases = ImmutableArray.Create( VariableAlias("a", "T[], 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "a[0].P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized generic type argument. aliases = ImmutableArray.Create( VariableAlias("s", "S`1[[T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]")); context.CompileExpression( "s.F", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void Variables() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { CheckVariable(runtime, "$exception", ExceptionAlias(), valid: true); CheckVariable(runtime, "$stowedexception", ExceptionAlias(stowed: true), valid: true); CheckVariable(runtime, "$Exception", ExceptionAlias(), valid: false); CheckVariable(runtime, "$STOWEDEXCEPTION", ExceptionAlias(stowed: true), valid: false); CheckVariable(runtime, "$ReturnValue", ReturnValueAlias(), valid: true); CheckVariable(runtime, "$RETURNVALUE", ReturnValueAlias(), valid: false); CheckVariable(runtime, "$returnvalue", ReturnValueAlias(), valid: true); // Lowercase $ReturnValue supported. CheckVariable(runtime, "$ReturnValue0", ReturnValueAlias(0), valid: true); CheckVariable(runtime, "$returnvalue21", ReturnValueAlias(21), valid: true); CheckVariable(runtime, "$ReturnValue3A", ReturnValueAlias(0x3a), valid: false); CheckVariable(runtime, "$33", ObjectIdAlias(33), valid: true); CheckVariable(runtime, "$03", ObjectIdAlias(3), valid: false); CheckVariable(runtime, "$3A", ObjectIdAlias(0x3a), valid: false); CheckVariable(runtime, "$0", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$Unknown", VariableAlias("x"), valid: false); }); } private void CheckVariable(RuntimeInstance runtime, string variableName, Alias alias, bool valid) { string error; var testData = Evaluate(runtime, "C.M", variableName, out error, alias); if (valid) { var expectedNames = new[] { "<>x.<>m0()" }; var actualNames = testData.GetMethodsByName().Keys; AssertEx.SetEqual(expectedNames, actualNames); } else { Assert.Equal(error, string.Format("error CS0103: The name '{0}' does not exist in the current context", variableName)); } } [Fact] public void CheckViability() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "$ReturnValue1<object>", out error, ReturnValueAlias(1)); Assert.Equal("error CS0307: The variable '$ReturnValue1' cannot be used with type arguments", error); testData = Evaluate( runtime, "C.M", "$ReturnValue2()", out error, ReturnValueAlias(2)); Assert.Equal("error CS0149: Method name expected", error); }); } /// <summary> /// $exception may be accessed from closure class. /// </summary> [Fact] public void ExceptionInDisplayClass() { var source = @"using System; class C { static object F(System.Func<object> f) { return f(); } static void M(object o) { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "F(() => o ?? $exception)", out error, ExceptionAlias()); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""object <>x.<>c__DisplayClass0_0.o"" IL_0006: dup IL_0007: brtrue.s IL_000f IL_0009: pop IL_000a: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000f: ret }"); }); } [Fact] public void AssignException() { var source = @"class C { static void M(System.Exception e) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias()); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileAssignment( target: "e", expr: "$exception.InnerException ?? $exception", aliases: aliases, formatter: DebuggerDiagnosticFormatter.Instance, resultProperties: out resultProperties, error: out error, missingAssemblyIdentities: out missingAssemblyIdentities, preferredUICulture: EnsureEnglishUICulture.PreferredOrNull, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: callvirt ""System.Exception System.Exception.InnerException.get"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0013: starg.s V_0 IL_0015: ret }"); }); } [Fact] public void AssignToException() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$exception = null", out error, ExceptionAlias()); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")] public void PassByRef() { var source = @"class C { static T F<T>(ref T t) { t = default(T); return t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.F"); var aliases = ImmutableArray.Create( ExceptionAlias(), ReturnValueAlias(), ObjectIdAlias(1), VariableAlias("x", typeof(int))); string error; // $exception context.CompileExpression( "$exception = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $exception)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object at address context.CompileExpression( "@0x123 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref @0x123)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // $ReturnValue context.CompileExpression( "$ReturnValue = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $ReturnValue)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object id context.CompileExpression( "$1 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $1)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Declared variable var testData = new CompilationTestData(); context.CompileExpression( "x = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 3 .locals init (T V_0, int V_1) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: ldc.i4.1 IL_000b: dup IL_000c: stloc.1 IL_000d: stind.i4 IL_000e: ldloc.1 IL_000f: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression( "F(ref x)", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (T V_0) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: call ""int C.F<int>(ref int)"" IL_000f: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ValueType() { var source = @"struct S { internal object F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 3 .locals init (object V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: dup IL_0011: stloc.0 IL_0012: stfld ""object S.F"" IL_0017: ldloc.0 IL_0018: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void CompoundAssignment() { var source = @"struct S { internal int F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F += 2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 24 (0x18) .maxstack 3 .locals init (int V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldflda ""int S.F"" IL_000f: dup IL_0010: ldind.i4 IL_0011: ldc.i4.2 IL_0012: add IL_0013: dup IL_0014: stloc.0 IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: ret }"); }); } /// <summary> /// Assembly-qualified type names from the debugger refer to runtime assemblies /// which may be different versions than the assembly references in metadata. /// </summary> [WorkItem(1087458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087458")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DifferentAssemblyVersion() { var sourceA = @"public class A<T> { }"; var sourceB = @"class B<T> { } class C { static void M() { var o = new A<object>(); } }"; const string assemblyNameA = "397300B0-A"; const string assemblyNameB = "397300B0-B"; var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationA1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); var compilationB1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 2, 2, 2)), new[] { sourceB }, references: new[] { MscorlibRef_v20, compilationA1.EmitToImageReference() }, options: TestOptions.DebugDll); // Use mscorlib v4.0.0.0 and A v2.1.2.1 at runtime. var compilationA2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 2, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); WithRuntimeInstance(compilationB1, new[] { MscorlibRef, compilationA2.EmitToImageReference() }, runtime => { // typeof(Exception), typeof(A<B<object>>), typeof(B<A<object>[]>) var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias("System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), ObjectIdAlias(1, "A`1[[B`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null]], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3"), ObjectIdAlias(2, "B`1[[A`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$exception ?? (object)$1 ?? $2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 2 .locals init (A<object> V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: dup IL_0006: brtrue.s IL_002b IL_0008: pop IL_0009: ldstr ""$1"" IL_000e: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0013: castclass ""A<B<object>>"" IL_0018: dup IL_0019: brtrue.s IL_002b IL_001b: pop IL_001c: ldstr ""$2"" IL_0021: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0026: castclass ""B<A<object>[]>"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type may reference an assembly /// outside of the current module and its references. /// </summary> [WorkItem(1092680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092680")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void TypeOutsideModule() { var sourceA = @"using System; public class A<T> { public static void M(Action f) { object o; try { f(); } catch (Exception) { } } }"; var sourceB = @"using System; class E : Exception { internal object F; } class B { static void Main() { A<int>.M(() => { throw new E(); }); } }"; var assemblyNameA = "0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: assemblyNameA); var moduleA = compilationA.ToModuleInstance(); var assemblyNameB = "9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9"; var compilationB = CreateCompilation(sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference() }, assemblyName: assemblyNameB); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance() , moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "A.M"); var aliases = ImmutableArray.Create( ExceptionAlias("E, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), ObjectIdAlias(1, "A`1[[B, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], 0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "$exception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 .locals init (object V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""E"" IL_000a: ret }"); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileAssignment( "o", "$1", aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 .locals init (object V_0) //o IL_0000: ldstr ""$1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""A<B>"" IL_000f: stloc.0 IL_0010: ret }"); } [WorkItem(1140387, "DevDiv")] [Fact] public void ReturnValueOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(ReturnValueAlias(type: typeof(int*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""System.IntPtr"" IL_000b: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0010: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1140387, "DevDiv")] public void UserVariableOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(VariableAlias("p", typeof(char*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "p", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 1 IL_0000: ldstr ""p"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""System.IntPtr"" IL_000f: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0014: ret }"); }); } private CompilationTestData Evaluate( RuntimeInstance runtime, string methodName, string expr, out string error, params Alias[] aliases) { var context = CreateMethodContext(runtime, methodName); var testData = new CompilationTestData(); var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(aliases), out error, testData); return testData; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class PseudoVariableTests : ExpressionCompilerTestBase { [Fact] public void UnrecognizedVariable() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$v", out error); Assert.Equal("error CS0103: The name '$v' does not exist in the current context", error); }); } [Fact] public void GlobalName() { var source = @"class C { static void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "global::$exception", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0400: The type or namespace name '$exception' could not be found in the global namespace (are you missing an assembly reference?)", error); } [Fact] public void QualifiedName() { var source = @"class C { void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( "this.$exception", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity); Assert.Equal("error CS1061: 'C' does not contain a definition for '$exception' and no accessible extension method '$exception' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)", error); }); } /// <summary> /// Generate call to intrinsic method for $exception, /// $stowedexception. /// </summary> [Fact] public void Exception() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(System.IO.IOException)), ExceptionAlias(typeof(InvalidOperationException), stowed: true)); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "(System.Exception)$exception ?? $stowedexception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""System.IO.IOException"" IL_000a: dup IL_000b: brtrue.s IL_0018 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetStowedException()"" IL_0013: castclass ""System.InvalidOperationException"" IL_0018: ret }"); }); } [Fact] public void ReturnValue() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(object)), ReturnValueAlias(2, typeof(string))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue ?? $ReturnValue2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: dup IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldc.i4.2 IL_000b: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0010: castclass ""string"" IL_0015: ret }"); // Value type $ReturnValue. context = CreateMethodContext( runtime, "C.M"); aliases = ImmutableArray.Create( ReturnValueAlias(type: typeof(int?))); testData = new CompilationTestData(); result = context.CompileExpression( "((int?)$ReturnValue).HasValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 20 (0x14) .maxstack 1 .locals init (int? V_0) IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int?"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""bool int?.HasValue.get"" IL_0013: ret }"); }); } /// <summary> /// Negative index should be treated as separate tokens. /// </summary> [Fact] public void ReturnValueNegative() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "(int)$ReturnValue-2", out error, ReturnValueAlias()); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""int"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: ret }"); }); } /// <summary> /// Dev12 syntax "[0-9]+#" not supported. /// </summary> [WorkItem(1071347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1071347")] [Fact] public void ObjectId_EarlierSyntax() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; context.CompileExpression( "23#", out error); Assert.Equal("error CS2043: 'id#' syntax is no longer supported. Use '$id' instead.", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ObjectId() { var source = @"class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( ObjectIdAlias(23, typeof(string)), ObjectIdAlias(4, typeof(Type))); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$23 ?? $4.BaseType", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal(1, testData.GetExplicitlyDeclaredMethods().Length); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 40 (0x28) .maxstack 2 IL_0000: ldstr ""$23"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""string"" IL_000f: dup IL_0010: brtrue.s IL_0027 IL_0012: pop IL_0013: ldstr ""$4"" IL_0018: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_001d: castclass ""System.Type"" IL_0022: callvirt ""System.Type System.Type.BaseType.get"" IL_0027: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1101017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101017")] public void NestedGenericValueType() { var source = @"class C { internal struct S<T> { internal T F; } static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "C+S`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "s.F + 1", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, null, // preferredUICulture testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 23 (0x17) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""C.S<int>"" IL_000f: ldfld ""int C.S<int>.F"" IL_0014: ldc.i4.1 IL_0015: add IL_0016: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ArrayType() { var source = @"class C { object F; static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("a", "C[]"), VariableAlias("b", "System.Int32[,], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileExpression( "a[b[1, 0]].F", DkmEvaluationFlags.TreatAsExpression, aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 4 IL_0000: ldstr ""a"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""C[]"" IL_000f: ldstr ""b"" IL_0014: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0019: castclass ""int[,]"" IL_001e: ldc.i4.1 IL_001f: ldc.i4.0 IL_0020: call ""int[*,*].Get"" IL_0025: ldelem.ref IL_0026: ldfld ""object C.F"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type name may be from an /// unrecognized assembly. For instance, if the type was /// defined in a previous evaluation, say an anonymous /// type (e.g.: evaluate "o" after "var o = new { P = 1 };"). /// </summary> [Fact] public void UnrecognizedAssembly() { var source = @"struct S<T> { internal T F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { string error; var testData = new CompilationTestData(); // Unrecognized type. var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("o", "T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "o.P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized array element type. aliases = ImmutableArray.Create( VariableAlias("a", "T[], 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); context.CompileExpression( "a[0].P", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); // Unrecognized generic type argument. aliases = ImmutableArray.Create( VariableAlias("s", "S`1[[T, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24AB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]")); context.CompileExpression( "s.F", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Equal("error CS0648: '' is a type not supported by the language", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void Variables() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { CheckVariable(runtime, "$exception", ExceptionAlias(), valid: true); CheckVariable(runtime, "$stowedexception", ExceptionAlias(stowed: true), valid: true); CheckVariable(runtime, "$Exception", ExceptionAlias(), valid: false); CheckVariable(runtime, "$STOWEDEXCEPTION", ExceptionAlias(stowed: true), valid: false); CheckVariable(runtime, "$ReturnValue", ReturnValueAlias(), valid: true); CheckVariable(runtime, "$RETURNVALUE", ReturnValueAlias(), valid: false); CheckVariable(runtime, "$returnvalue", ReturnValueAlias(), valid: true); // Lowercase $ReturnValue supported. CheckVariable(runtime, "$ReturnValue0", ReturnValueAlias(0), valid: true); CheckVariable(runtime, "$returnvalue21", ReturnValueAlias(21), valid: true); CheckVariable(runtime, "$ReturnValue3A", ReturnValueAlias(0x3a), valid: false); CheckVariable(runtime, "$33", ObjectIdAlias(33), valid: true); CheckVariable(runtime, "$03", ObjectIdAlias(3), valid: false); CheckVariable(runtime, "$3A", ObjectIdAlias(0x3a), valid: false); CheckVariable(runtime, "$0", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$", ObjectIdAlias(1), valid: false); CheckVariable(runtime, "$Unknown", VariableAlias("x"), valid: false); }); } private void CheckVariable(RuntimeInstance runtime, string variableName, Alias alias, bool valid) { string error; var testData = Evaluate(runtime, "C.M", variableName, out error, alias); if (valid) { var expectedNames = new[] { "<>x.<>m0()" }; var actualNames = testData.GetMethodsByName().Keys; AssertEx.SetEqual(expectedNames, actualNames); } else { Assert.Equal(error, string.Format("error CS0103: The name '{0}' does not exist in the current context", variableName)); } } [Fact] public void CheckViability() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "$ReturnValue1<object>", out error, ReturnValueAlias(1)); Assert.Equal("error CS0307: The variable '$ReturnValue1' cannot be used with type arguments", error); testData = Evaluate( runtime, "C.M", "$ReturnValue2()", out error, ReturnValueAlias(2)); Assert.Equal("error CS0149: Method name expected", error); }); } /// <summary> /// $exception may be accessed from closure class. /// </summary> [Fact] public void ExceptionInDisplayClass() { var source = @"using System; class C { static object F(System.Func<object> f) { return f(); } static void M(object o) { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; var testData = Evaluate( runtime, "C.M", "F(() => o ?? $exception)", out error, ExceptionAlias()); testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<>m0>b__0()").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""object <>x.<>c__DisplayClass0_0.o"" IL_0006: dup IL_0007: brtrue.s IL_000f IL_0009: pop IL_000a: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000f: ret }"); }); } [Fact] public void AssignException() { var source = @"class C { static void M(System.Exception e) { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias()); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); context.CompileAssignment( target: "e", expr: "$exception.InnerException ?? $exception", aliases: aliases, formatter: DebuggerDiagnosticFormatter.Instance, resultProperties: out resultProperties, error: out error, missingAssemblyIdentities: out missingAssemblyIdentities, preferredUICulture: EnsureEnglishUICulture.PreferredOrNull, testData: testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 22 (0x16) .maxstack 2 IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: callvirt ""System.Exception System.Exception.InnerException.get"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0013: starg.s V_0 IL_0015: ret }"); }); } [Fact] public void AssignToException() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { string error; Evaluate(runtime, "C.M", "$exception = null", out error, ExceptionAlias()); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1100849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100849")] public void PassByRef() { var source = @"class C { static T F<T>(ref T t) { t = default(T); return t; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.F"); var aliases = ImmutableArray.Create( ExceptionAlias(), ReturnValueAlias(), ObjectIdAlias(1), VariableAlias("x", typeof(int))); string error; // $exception context.CompileExpression( "$exception = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $exception)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object at address context.CompileExpression( "@0x123 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref @0x123)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // $ReturnValue context.CompileExpression( "$ReturnValue = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $ReturnValue)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Object id context.CompileExpression( "$1 = null", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS0131: The left-hand side of an assignment must be a variable, property or indexer", error); context.CompileExpression( "F(ref $1)", DkmEvaluationFlags.TreatAsExpression, aliases, out error); Assert.Equal("error CS1510: A ref or out value must be an assignable variable", error); // Declared variable var testData = new CompilationTestData(); context.CompileExpression( "x = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 3 .locals init (T V_0, int V_1) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: ldc.i4.1 IL_000b: dup IL_000c: stloc.1 IL_000d: stind.i4 IL_000e: ldloc.1 IL_000f: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression( "F(ref x)", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0<T>").VerifyIL( @"{ // Code size 16 (0x10) .maxstack 1 .locals init (T V_0) IL_0000: ldstr ""x"" IL_0005: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)"" IL_000a: call ""int C.F<int>(ref int)"" IL_000f: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void ValueType() { var source = @"struct S { internal object F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F = 1", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 25 (0x19) .maxstack 3 .locals init (object V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldc.i4.1 IL_000b: box ""int"" IL_0010: dup IL_0011: stloc.0 IL_0012: stfld ""object S.F"" IL_0017: ldloc.0 IL_0018: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void CompoundAssignment() { var source = @"struct S { internal int F; } class C { static void M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "S")); string error; var testData = new CompilationTestData(); context.CompileExpression( "s.F += 2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 24 (0x18) .maxstack 3 .locals init (int V_0) IL_0000: ldstr ""s"" IL_0005: call ""S Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S>(string)"" IL_000a: ldflda ""int S.F"" IL_000f: dup IL_0010: ldind.i4 IL_0011: ldc.i4.2 IL_0012: add IL_0013: dup IL_0014: stloc.0 IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: ret }"); }); } /// <summary> /// Assembly-qualified type names from the debugger refer to runtime assemblies /// which may be different versions than the assembly references in metadata. /// </summary> [WorkItem(1087458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087458")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DifferentAssemblyVersion() { var sourceA = @"public class A<T> { }"; var sourceB = @"class B<T> { } class C { static void M() { var o = new A<object>(); } }"; const string assemblyNameA = "397300B0-A"; const string assemblyNameB = "397300B0-B"; var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationA1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); var compilationB1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 2, 2, 2)), new[] { sourceB }, references: new[] { MscorlibRef_v20, compilationA1.EmitToImageReference() }, options: TestOptions.DebugDll); // Use mscorlib v4.0.0.0 and A v2.1.2.1 at runtime. var compilationA2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 2, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef_v20 }, options: TestOptions.DebugDll.WithDelaySign(true)); WithRuntimeInstance(compilationB1, new[] { MscorlibRef, compilationA2.EmitToImageReference() }, runtime => { // typeof(Exception), typeof(A<B<object>>), typeof(B<A<object>[]>) var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create( ExceptionAlias("System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), ObjectIdAlias(1, "A`1[[B`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null]], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3"), ObjectIdAlias(2, "B`1[[A`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][], 397300B0-A, Version=2.1.2.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3]], 397300B0-B, Version=1.2.2.2, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)$exception ?? (object)$1 ?? $2", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 44 (0x2c) .maxstack 2 .locals init (A<object> V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: dup IL_0006: brtrue.s IL_002b IL_0008: pop IL_0009: ldstr ""$1"" IL_000e: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0013: castclass ""A<B<object>>"" IL_0018: dup IL_0019: brtrue.s IL_002b IL_001b: pop IL_001c: ldstr ""$2"" IL_0021: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0026: castclass ""B<A<object>[]>"" IL_002b: ret }"); }); } /// <summary> /// The assembly-qualified type may reference an assembly /// outside of the current module and its references. /// </summary> [WorkItem(1092680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092680")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void TypeOutsideModule() { var sourceA = @"using System; public class A<T> { public static void M(Action f) { object o; try { f(); } catch (Exception) { } } }"; var sourceB = @"using System; class E : Exception { internal object F; } class B { static void Main() { A<int>.M(() => { throw new E(); }); } }"; var assemblyNameA = "0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: assemblyNameA); var moduleA = compilationA.ToModuleInstance(); var assemblyNameB = "9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9"; var compilationB = CreateCompilation(sourceB, options: TestOptions.DebugExe, references: new[] { moduleA.GetReference() }, assemblyName: assemblyNameB); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance() , moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "A.M"); var aliases = ImmutableArray.Create( ExceptionAlias("E, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), ObjectIdAlias(1, "A`1[[B, 9BAC6622-86EB-4EC5-94A1-9A1E6D0C24B9, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], 0A93FF0B-31A2-47C8-B24D-16A2D77AB5C5, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); string error; var testData = new CompilationTestData(); context.CompileExpression( "$exception", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 11 (0xb) .maxstack 1 .locals init (object V_0) //o IL_0000: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_0005: castclass ""E"" IL_000a: ret }"); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileAssignment( "o", "$1", aliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); Assert.Null(error); testData.GetMethodData("<>x<T>.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 .locals init (object V_0) //o IL_0000: ldstr ""$1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""A<B>"" IL_000f: stloc.0 IL_0010: ret }"); } [WorkItem(1140387, "DevDiv")] [Fact] public void ReturnValueOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(ReturnValueAlias(type: typeof(int*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "$ReturnValue", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Int32, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_0006: unbox.any ""System.IntPtr"" IL_000b: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0010: ret }"); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1140387, "DevDiv")] public void UserVariableOfPointerType() { var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName()); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var aliases = ImmutableArray.Create(VariableAlias("p", typeof(char*))); string error; var testData = new CompilationTestData(); var result = context.CompileExpression( "p", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)((MethodSymbol)methodData.Method).ReturnType).PointedAtType.SpecialType); methodData.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 1 IL_0000: ldstr ""p"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: unbox.any ""System.IntPtr"" IL_000f: call ""void* System.IntPtr.op_Explicit(System.IntPtr)"" IL_0014: ret }"); }); } private CompilationTestData Evaluate( RuntimeInstance runtime, string methodName, string expr, out string error, params Alias[] aliases) { var context = CreateMethodContext(runtime, methodName); var testData = new CompilationTestData(); var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create(aliases), out error, testData); return testData; } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Analyzers/CSharp/Analyzers/UseSimpleUsingStatement/UseSimpleUsingStatementDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement { /// <summary> /// Looks for code like: /// /// ```c# /// using (var a = b) /// using (var c = d) /// using (var e = f) /// { /// } /// ``` /// /// And offers to convert it to: /// /// ```c# /// using var a = b; /// using var c = d; /// using var e = f; /// ``` /// /// (this of course works in the case where there is only one using). /// /// A few design decisions: /// /// 1. We only offer this if the entire group of usings in a nested stack can be /// converted. We don't want to take a nice uniform group and break it into /// a combination of using-statements and using-declarations. That may feel /// less pleasant to the user than just staying uniform. /// /// 2. We're conservative about converting. Because `using`s may be critical for /// program correctness, we only convert when we're absolutely *certain* that /// semantics will not change. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class UseSimpleUsingStatementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public UseSimpleUsingStatementDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId, EnforceOnBuildValues.UseSimpleUsingStatement, CSharpCodeStyleOptions.PreferSimpleUsingStatement, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_simple_using_statement), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.using_statement_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.UsingStatement); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var outermostUsing = (UsingStatementSyntax)context.Node; var syntaxTree = context.Node.SyntaxTree; var options = (CSharpParseOptions)syntaxTree.Options; if (options.LanguageVersion < LanguageVersion.CSharp8) { return; } if (outermostUsing.Parent is not BlockSyntax parentBlock) { // Don't offer on a using statement that is parented by another using statement. // We'll just offer on the topmost using statement. return; } var innermostUsing = outermostUsing; // Check that all the immediately nested usings are convertible as well. // We don't want take a sequence of nested-using and only convert some of them. for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax) { innermostUsing = current; if (current.Declaration == null) { return; } } // Verify that changing this using-statement into a using-declaration will not // change semantics. if (!PreservesSemantics(parentBlock, outermostUsing, innermostUsing)) { return; } var cancellationToken = context.CancellationToken; // Converting a using-statement to a using-variable-declaration will cause the using's // variables to now be pushed up to the parent block's scope. This is also true for any // local variables in the innermost using's block. These may then collide with other // variables in the block, causing an error. Check for that and bail if this happens. if (CausesVariableCollision( context.SemanticModel, parentBlock, outermostUsing, innermostUsing, cancellationToken)) { return; } var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferSimpleUsingStatement, syntaxTree, cancellationToken); if (!option.Value) { return; } // Good to go! context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, outermostUsing.UsingKeyword.GetLocation(), option.Notification.Severity, additionalLocations: ImmutableArray.Create(outermostUsing.GetLocation()), properties: null)); } private static bool CausesVariableCollision( SemanticModel semanticModel, BlockSyntax parentBlock, UsingStatementSyntax outermostUsing, UsingStatementSyntax innermostUsing, CancellationToken cancellationToken) { var symbolNameToExistingSymbol = semanticModel.GetExistingSymbols(parentBlock, cancellationToken).ToLookup(s => s.Name); for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax) { // Check if the using statement itself contains variables that will collide // with other variables in the block. var usingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(current, cancellationToken); if (DeclaredLocalCausesCollision(symbolNameToExistingSymbol, usingOperation.Locals)) return true; } var innerUsingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(innermostUsing, cancellationToken); if (innerUsingOperation.Body is IBlockOperation innerUsingBlock) return DeclaredLocalCausesCollision(symbolNameToExistingSymbol, innerUsingBlock.Locals); return false; } private static bool DeclaredLocalCausesCollision(ILookup<string, ISymbol> symbolNameToExistingSymbol, ImmutableArray<ILocalSymbol> locals) => locals.Any(local => symbolNameToExistingSymbol[local.Name].Any(otherLocal => !local.Equals(otherLocal))); private static bool PreservesSemantics( BlockSyntax parentBlock, UsingStatementSyntax outermostUsing, UsingStatementSyntax innermostUsing) { var statements = parentBlock.Statements; var index = statements.IndexOf(outermostUsing); return UsingValueDoesNotLeakToFollowingStatements(statements, index) && UsingStatementDoesNotInvolveJumps(statements, index, innermostUsing); } private static bool UsingStatementDoesNotInvolveJumps( SyntaxList<StatementSyntax> parentStatements, int index, UsingStatementSyntax innermostUsing) { // Jumps are not allowed to cross a using declaration in the forward direction, // and can't go back unless there is a curly brace between the using and the label. // // We conservatively implement this by disallowing the change if there are gotos/labels // in the containing block, or inside the using body. // Note: we only have to check up to the `using`, since the checks below in // UsingValueDoesNotLeakToFollowingStatements ensure that there would be no // labels/gotos *after* the using statement. for (var i = 0; i < index; i++) { var priorStatement = parentStatements[i]; if (IsGotoOrLabeledStatement(priorStatement)) { return false; } } var innerStatements = innermostUsing.Statement is BlockSyntax block ? block.Statements : new SyntaxList<StatementSyntax>(innermostUsing.Statement); foreach (var statement in innerStatements) { if (IsGotoOrLabeledStatement(statement)) { return false; } } return true; } private static bool IsGotoOrLabeledStatement(StatementSyntax priorStatement) => priorStatement.Kind() == SyntaxKind.GotoStatement || priorStatement.Kind() == SyntaxKind.LabeledStatement; private static bool UsingValueDoesNotLeakToFollowingStatements( SyntaxList<StatementSyntax> statements, int index) { // Has to be one of the following forms: // 1. Using statement is the last statement in the parent. // 2. Using statement is not the last statement in parent, but is followed by // something that is unaffected by simplifying the using statement. i.e. // `return`/`break`/`continue`. *Note*. `return expr` would *not* be ok. // In that case, `expr` would now be evaluated *before* the using disposed // the resource, instead of afterwards. Effectly, the statement following // cannot actually execute any code that might depend on the .Dispose method // being called or not. if (index == statements.Count - 1) { // very last statement in the block. Can be converted. return true; } // Not the last statement, get the next statement and examine that. var nextStatement = statements[index + 1]; if (nextStatement is BreakStatementSyntax || nextStatement is ContinueStatementSyntax) { // using statement followed by break/continue. Can convert this as executing // the break/continue will cause the code to exit the using scope, causing // Dispose to be called at the same place as before. return true; } if (nextStatement is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { // using statement followed by `return`. Can conver this as executing // the `return` will cause the code to exit the using scope, causing // Dispose to be called at the same place as before. // // Note: the expr has to be null. If it was non-null, then the expr would // now execute before hte using called 'Dispose' instead of after, potentially // changing semantics. return true; } // Add any additional cases here in the future. 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.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseSimpleUsingStatement { /// <summary> /// Looks for code like: /// /// ```c# /// using (var a = b) /// using (var c = d) /// using (var e = f) /// { /// } /// ``` /// /// And offers to convert it to: /// /// ```c# /// using var a = b; /// using var c = d; /// using var e = f; /// ``` /// /// (this of course works in the case where there is only one using). /// /// A few design decisions: /// /// 1. We only offer this if the entire group of usings in a nested stack can be /// converted. We don't want to take a nice uniform group and break it into /// a combination of using-statements and using-declarations. That may feel /// less pleasant to the user than just staying uniform. /// /// 2. We're conservative about converting. Because `using`s may be critical for /// program correctness, we only convert when we're absolutely *certain* that /// semantics will not change. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class UseSimpleUsingStatementDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public UseSimpleUsingStatementDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSimpleUsingStatementDiagnosticId, EnforceOnBuildValues.UseSimpleUsingStatement, CSharpCodeStyleOptions.PreferSimpleUsingStatement, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_simple_using_statement), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.using_statement_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.UsingStatement); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var outermostUsing = (UsingStatementSyntax)context.Node; var syntaxTree = context.Node.SyntaxTree; var options = (CSharpParseOptions)syntaxTree.Options; if (options.LanguageVersion < LanguageVersion.CSharp8) { return; } if (outermostUsing.Parent is not BlockSyntax parentBlock) { // Don't offer on a using statement that is parented by another using statement. // We'll just offer on the topmost using statement. return; } var innermostUsing = outermostUsing; // Check that all the immediately nested usings are convertible as well. // We don't want take a sequence of nested-using and only convert some of them. for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax) { innermostUsing = current; if (current.Declaration == null) { return; } } // Verify that changing this using-statement into a using-declaration will not // change semantics. if (!PreservesSemantics(parentBlock, outermostUsing, innermostUsing)) { return; } var cancellationToken = context.CancellationToken; // Converting a using-statement to a using-variable-declaration will cause the using's // variables to now be pushed up to the parent block's scope. This is also true for any // local variables in the innermost using's block. These may then collide with other // variables in the block, causing an error. Check for that and bail if this happens. if (CausesVariableCollision( context.SemanticModel, parentBlock, outermostUsing, innermostUsing, cancellationToken)) { return; } var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferSimpleUsingStatement, syntaxTree, cancellationToken); if (!option.Value) { return; } // Good to go! context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, outermostUsing.UsingKeyword.GetLocation(), option.Notification.Severity, additionalLocations: ImmutableArray.Create(outermostUsing.GetLocation()), properties: null)); } private static bool CausesVariableCollision( SemanticModel semanticModel, BlockSyntax parentBlock, UsingStatementSyntax outermostUsing, UsingStatementSyntax innermostUsing, CancellationToken cancellationToken) { var symbolNameToExistingSymbol = semanticModel.GetExistingSymbols(parentBlock, cancellationToken).ToLookup(s => s.Name); for (var current = outermostUsing; current != null; current = current.Statement as UsingStatementSyntax) { // Check if the using statement itself contains variables that will collide // with other variables in the block. var usingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(current, cancellationToken); if (DeclaredLocalCausesCollision(symbolNameToExistingSymbol, usingOperation.Locals)) return true; } var innerUsingOperation = (IUsingOperation)semanticModel.GetRequiredOperation(innermostUsing, cancellationToken); if (innerUsingOperation.Body is IBlockOperation innerUsingBlock) return DeclaredLocalCausesCollision(symbolNameToExistingSymbol, innerUsingBlock.Locals); return false; } private static bool DeclaredLocalCausesCollision(ILookup<string, ISymbol> symbolNameToExistingSymbol, ImmutableArray<ILocalSymbol> locals) => locals.Any(local => symbolNameToExistingSymbol[local.Name].Any(otherLocal => !local.Equals(otherLocal))); private static bool PreservesSemantics( BlockSyntax parentBlock, UsingStatementSyntax outermostUsing, UsingStatementSyntax innermostUsing) { var statements = parentBlock.Statements; var index = statements.IndexOf(outermostUsing); return UsingValueDoesNotLeakToFollowingStatements(statements, index) && UsingStatementDoesNotInvolveJumps(statements, index, innermostUsing); } private static bool UsingStatementDoesNotInvolveJumps( SyntaxList<StatementSyntax> parentStatements, int index, UsingStatementSyntax innermostUsing) { // Jumps are not allowed to cross a using declaration in the forward direction, // and can't go back unless there is a curly brace between the using and the label. // // We conservatively implement this by disallowing the change if there are gotos/labels // in the containing block, or inside the using body. // Note: we only have to check up to the `using`, since the checks below in // UsingValueDoesNotLeakToFollowingStatements ensure that there would be no // labels/gotos *after* the using statement. for (var i = 0; i < index; i++) { var priorStatement = parentStatements[i]; if (IsGotoOrLabeledStatement(priorStatement)) { return false; } } var innerStatements = innermostUsing.Statement is BlockSyntax block ? block.Statements : new SyntaxList<StatementSyntax>(innermostUsing.Statement); foreach (var statement in innerStatements) { if (IsGotoOrLabeledStatement(statement)) { return false; } } return true; } private static bool IsGotoOrLabeledStatement(StatementSyntax priorStatement) => priorStatement.Kind() == SyntaxKind.GotoStatement || priorStatement.Kind() == SyntaxKind.LabeledStatement; private static bool UsingValueDoesNotLeakToFollowingStatements( SyntaxList<StatementSyntax> statements, int index) { // Has to be one of the following forms: // 1. Using statement is the last statement in the parent. // 2. Using statement is not the last statement in parent, but is followed by // something that is unaffected by simplifying the using statement. i.e. // `return`/`break`/`continue`. *Note*. `return expr` would *not* be ok. // In that case, `expr` would now be evaluated *before* the using disposed // the resource, instead of afterwards. Effectly, the statement following // cannot actually execute any code that might depend on the .Dispose method // being called or not. if (index == statements.Count - 1) { // very last statement in the block. Can be converted. return true; } // Not the last statement, get the next statement and examine that. var nextStatement = statements[index + 1]; if (nextStatement is BreakStatementSyntax || nextStatement is ContinueStatementSyntax) { // using statement followed by break/continue. Can convert this as executing // the break/continue will cause the code to exit the using scope, causing // Dispose to be called at the same place as before. return true; } if (nextStatement is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { // using statement followed by `return`. Can conver this as executing // the `return` will cause the code to exit the using scope, causing // Dispose to be called at the same place as before. // // Note: the expr has to be null. If it was non-null, then the expr would // now execute before hte using called 'Dispose' instead of after, potentially // changing semantics. return true; } // Add any additional cases here in the future. return false; } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/Core/Portable/DiaSymReader/Metadata/MetadataAdapterBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Reflection; namespace Microsoft.DiaSymReader { internal unsafe class MetadataAdapterBase : IMetadataImport, IMetadataEmit { public virtual int GetTokenFromSig(byte* voidPointerSig, int byteCountSig) => throw new NotImplementedException(); public virtual int GetSigFromToken( int standaloneSignature, [Out] byte** signature, [Out] int* signatureLength) => throw new NotImplementedException(); public virtual int GetTypeDefProps( int typeDef, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength, [Out] TypeAttributes* attributes, [Out] int* baseType) => throw new NotImplementedException(); public virtual int GetTypeRefProps( int typeRef, [Out] int* resolutionScope, // ModuleRef or AssemblyRef [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength) => throw new NotImplementedException(); public virtual int GetNestedClassProps(int nestedClass, out int enclosingClass) => throw new NotImplementedException(); public virtual int GetMethodProps( int methodDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] MethodAttributes* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] MethodImplAttributes* implAttributes) => throw new NotImplementedException(); void IMetadataImport.CloseEnum(void* enumHandle) => throw new NotImplementedException(); int IMetadataImport.CountEnum(void* enumHandle, out int count) => throw new NotImplementedException(); int IMetadataImport.ResetEnum(void* enumHandle, int position) => throw new NotImplementedException(); int IMetadataImport.EnumTypeDefs(ref void* enumHandle, int* typeDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumInterfaceImpls(ref void* enumHandle, int typeDef, int* interfaceImpls, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumTypeRefs(ref void* enumHandle, int* typeRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.FindTypeDefByName(string name, int enclosingClass, out int typeDef) => throw new NotImplementedException(); int IMetadataImport.GetScopeProps(char* name, int bufferLength, int* nameLength, Guid* mvid) => throw new NotImplementedException(); int IMetadataImport.GetModuleFromScope(out int moduleDef) => throw new NotImplementedException(); int IMetadataImport.GetInterfaceImplProps(int interfaceImpl, int* typeDef, int* interfaceDefRefSpec) => throw new NotImplementedException(); int IMetadataImport.ResolveTypeRef(int typeRef, ref Guid scopeInterfaceId, out object scope, out int typeDef) => throw new NotImplementedException(); int IMetadataImport.EnumMembers(ref void* enumHandle, int typeDef, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMembersWithName(ref void* enumHandle, int typeDef, string name, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethods(ref void* enumHandle, int typeDef, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumFields(ref void* enumHandle, int typeDef, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumParams(ref void* enumHandle, int methodDef, int* paramDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMemberRefs(ref void* enumHandle, int parentToken, int* memberRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethodImpls(ref void* enumHandle, int typeDef, int* implementationTokens, int* declarationTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumPermissionSets(ref void* enumHandle, int token, uint action, int* declSecurityTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.FindMember(int typeDef, string name, byte* signature, int signatureLength, out int memberDef) => throw new NotImplementedException(); int IMetadataImport.FindMethod(int typeDef, string name, byte* signature, int signatureLength, out int methodDef) => throw new NotImplementedException(); int IMetadataImport.FindField(int typeDef, string name, byte* signature, int signatureLength, out int fieldDef) => throw new NotImplementedException(); int IMetadataImport.FindMemberRef(int typeDef, string name, byte* signature, int signatureLength, out int memberRef) => throw new NotImplementedException(); int IMetadataImport.GetMemberRefProps(int memberRef, int* declaringType, char* name, int nameBufferLength, int* nameLength, byte** signature, int* signatureLength) => throw new NotImplementedException(); int IMetadataImport.EnumProperties(ref void* enumHandle, int typeDef, int* properties, int bufferLength, int* count) => throw new NotImplementedException(); uint IMetadataImport.EnumEvents(ref void* enumHandle, int typeDef, int* events, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetEventProps(int @event, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, int* eventType, int* adderMethodDef, int* removerMethodDef, int* raiserMethodDef, int* otherMethodDefs, int otherMethodDefBufferLength, int* methodMethodDefsLength) => throw new NotImplementedException(); int IMetadataImport.EnumMethodSemantics(ref void* enumHandle, int methodDef, int* eventsAndProperties, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetMethodSemantics(int methodDef, int eventOrProperty, int* semantics) => throw new NotImplementedException(); int IMetadataImport.GetClassLayout(int typeDef, int* packSize, MetadataImportFieldOffset* fieldOffsets, int bufferLength, int* count, int* typeSize) => throw new NotImplementedException(); int IMetadataImport.GetFieldMarshal(int fieldDef, byte** nativeTypeSignature, int* nativeTypeSignatureLengvth) => throw new NotImplementedException(); int IMetadataImport.GetRVA(int methodDef, int* relativeVirtualAddress, int* implAttributes) => throw new NotImplementedException(); int IMetadataImport.GetPermissionSetProps(int declSecurity, uint* action, byte** permissionBlob, int* permissionBlobLength) => throw new NotImplementedException(); int IMetadataImport.GetModuleRefProps(int moduleRef, char* name, int nameBufferLength, int* nameLength) => throw new NotImplementedException(); int IMetadataImport.EnumModuleRefs(ref void* enumHandle, int* moduleRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetTypeSpecFromToken(int typeSpec, byte** signature, int* signatureLength) => throw new NotImplementedException(); int IMetadataImport.GetNameFromToken(int token, byte* nameUTF8) => throw new NotImplementedException(); int IMetadataImport.EnumUnresolvedMethods(ref void* enumHandle, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetUserString(int userStringToken, char* buffer, int bufferLength, int* length) => throw new NotImplementedException(); int IMetadataImport.GetPinvokeMap(int memberDef, int* attributes, char* importName, int importNameBufferLength, int* importNameLength, int* moduleRef) => throw new NotImplementedException(); int IMetadataImport.EnumSignatures(ref void* enumHandle, int* signatureTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumTypeSpecs(ref void* enumHandle, int* typeSpecs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumUserStrings(ref void* enumHandle, int* userStrings, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken) => throw new NotImplementedException(); int IMetadataImport.EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, int* customAttributes, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetCustomAttributeProps(int customAttribute, int* parent, int* constructor, byte** value, int* valueLength) => throw new NotImplementedException(); int IMetadataImport.FindTypeRef(int resolutionScope, string name, out int typeRef) => throw new NotImplementedException(); int IMetadataImport.GetMemberProps(int member, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* relativeVirtualAddress, int* implAttributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetFieldProps(int fieldDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetPropertyProps(int propertyDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength, int* setterMethodDef, int* getterMethodDef, int* outerMethodDefs, int outerMethodDefsBufferLength, int* otherMethodDefCount) => throw new NotImplementedException(); int IMetadataImport.GetParamProps(int parameter, int* declaringMethodDef, int* sequenceNumber, char* name, int nameBufferLength, int* nameLength, int* attributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetCustomAttributeByName(int parent, string name, byte** value, int* valueLength) => throw new NotImplementedException(); bool IMetadataImport.IsValidToken(int token) => throw new NotImplementedException(); int IMetadataImport.GetNativeCallConvFromSig(byte* signature, int signatureLength, int* callingConvention) => throw new NotImplementedException(); int IMetadataImport.IsGlobal(int token, bool value) => throw new NotImplementedException(); void IMetadataEmit.__SetModuleProps() => throw new NotImplementedException(); void IMetadataEmit.__Save() => throw new NotImplementedException(); void IMetadataEmit.__SaveToStream() => throw new NotImplementedException(); void IMetadataEmit.__GetSaveSize() => throw new NotImplementedException(); void IMetadataEmit.__DefineTypeDef() => throw new NotImplementedException(); void IMetadataEmit.__DefineNestedType() => throw new NotImplementedException(); void IMetadataEmit.__SetHandler() => throw new NotImplementedException(); void IMetadataEmit.__DefineMethod() => throw new NotImplementedException(); void IMetadataEmit.__DefineMethodImpl() => throw new NotImplementedException(); void IMetadataEmit.__DefineTypeRefByName() => throw new NotImplementedException(); void IMetadataEmit.__DefineImportType() => throw new NotImplementedException(); void IMetadataEmit.__DefineMemberRef() => throw new NotImplementedException(); void IMetadataEmit.__DefineImportMember() => throw new NotImplementedException(); void IMetadataEmit.__DefineEvent() => throw new NotImplementedException(); void IMetadataEmit.__SetClassLayout() => throw new NotImplementedException(); void IMetadataEmit.__DeleteClassLayout() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldMarshal() => throw new NotImplementedException(); void IMetadataEmit.__DeleteFieldMarshal() => throw new NotImplementedException(); void IMetadataEmit.__DefinePermissionSet() => throw new NotImplementedException(); void IMetadataEmit.__SetRVA() => throw new NotImplementedException(); void IMetadataEmit.__DefineModuleRef() => throw new NotImplementedException(); void IMetadataEmit.__SetParent() => throw new NotImplementedException(); void IMetadataEmit.__GetTokenFromTypeSpec() => throw new NotImplementedException(); void IMetadataEmit.__SaveToMemory() => throw new NotImplementedException(); void IMetadataEmit.__DefineUserString() => throw new NotImplementedException(); void IMetadataEmit.__DeleteToken() => throw new NotImplementedException(); void IMetadataEmit.__SetMethodProps() => throw new NotImplementedException(); void IMetadataEmit.__SetTypeDefProps() => throw new NotImplementedException(); void IMetadataEmit.__SetEventProps() => throw new NotImplementedException(); void IMetadataEmit.__SetPermissionSetProps() => throw new NotImplementedException(); void IMetadataEmit.__DefinePinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__SetPinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__DeletePinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__DefineCustomAttribute() => throw new NotImplementedException(); void IMetadataEmit.__SetCustomAttributeValue() => throw new NotImplementedException(); void IMetadataEmit.__DefineField() => throw new NotImplementedException(); void IMetadataEmit.__DefineProperty() => throw new NotImplementedException(); void IMetadataEmit.__DefineParam() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldProps() => throw new NotImplementedException(); void IMetadataEmit.__SetPropertyProps() => throw new NotImplementedException(); void IMetadataEmit.__SetParamProps() => throw new NotImplementedException(); void IMetadataEmit.__DefineSecurityAttributeSet() => throw new NotImplementedException(); void IMetadataEmit.__ApplyEditAndContinue() => throw new NotImplementedException(); void IMetadataEmit.__TranslateSigWithScope() => throw new NotImplementedException(); void IMetadataEmit.__SetMethodImplFlags() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldRVA() => throw new NotImplementedException(); void IMetadataEmit.__Merge() => throw new NotImplementedException(); void IMetadataEmit.__MergeEnd() => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Reflection; namespace Microsoft.DiaSymReader { internal unsafe class MetadataAdapterBase : IMetadataImport, IMetadataEmit { public virtual int GetTokenFromSig(byte* voidPointerSig, int byteCountSig) => throw new NotImplementedException(); public virtual int GetSigFromToken( int standaloneSignature, [Out] byte** signature, [Out] int* signatureLength) => throw new NotImplementedException(); public virtual int GetTypeDefProps( int typeDef, [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength, [Out] TypeAttributes* attributes, [Out] int* baseType) => throw new NotImplementedException(); public virtual int GetTypeRefProps( int typeRef, [Out] int* resolutionScope, // ModuleRef or AssemblyRef [Out] char* qualifiedName, int qualifiedNameBufferLength, [Out] int* qualifiedNameLength) => throw new NotImplementedException(); public virtual int GetNestedClassProps(int nestedClass, out int enclosingClass) => throw new NotImplementedException(); public virtual int GetMethodProps( int methodDef, [Out] int* declaringTypeDef, [Out] char* name, int nameBufferLength, [Out] int* nameLength, [Out] MethodAttributes* attributes, [Out] byte** signature, [Out] int* signatureLength, [Out] int* relativeVirtualAddress, [Out] MethodImplAttributes* implAttributes) => throw new NotImplementedException(); void IMetadataImport.CloseEnum(void* enumHandle) => throw new NotImplementedException(); int IMetadataImport.CountEnum(void* enumHandle, out int count) => throw new NotImplementedException(); int IMetadataImport.ResetEnum(void* enumHandle, int position) => throw new NotImplementedException(); int IMetadataImport.EnumTypeDefs(ref void* enumHandle, int* typeDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumInterfaceImpls(ref void* enumHandle, int typeDef, int* interfaceImpls, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumTypeRefs(ref void* enumHandle, int* typeRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.FindTypeDefByName(string name, int enclosingClass, out int typeDef) => throw new NotImplementedException(); int IMetadataImport.GetScopeProps(char* name, int bufferLength, int* nameLength, Guid* mvid) => throw new NotImplementedException(); int IMetadataImport.GetModuleFromScope(out int moduleDef) => throw new NotImplementedException(); int IMetadataImport.GetInterfaceImplProps(int interfaceImpl, int* typeDef, int* interfaceDefRefSpec) => throw new NotImplementedException(); int IMetadataImport.ResolveTypeRef(int typeRef, ref Guid scopeInterfaceId, out object scope, out int typeDef) => throw new NotImplementedException(); int IMetadataImport.EnumMembers(ref void* enumHandle, int typeDef, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMembersWithName(ref void* enumHandle, int typeDef, string name, int* memberDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethods(ref void* enumHandle, int typeDef, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethodsWithName(ref void* enumHandle, int typeDef, string name, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumFields(ref void* enumHandle, int typeDef, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumFieldsWithName(ref void* enumHandle, int typeDef, string name, int* fieldDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumParams(ref void* enumHandle, int methodDef, int* paramDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMemberRefs(ref void* enumHandle, int parentToken, int* memberRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumMethodImpls(ref void* enumHandle, int typeDef, int* implementationTokens, int* declarationTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumPermissionSets(ref void* enumHandle, int token, uint action, int* declSecurityTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.FindMember(int typeDef, string name, byte* signature, int signatureLength, out int memberDef) => throw new NotImplementedException(); int IMetadataImport.FindMethod(int typeDef, string name, byte* signature, int signatureLength, out int methodDef) => throw new NotImplementedException(); int IMetadataImport.FindField(int typeDef, string name, byte* signature, int signatureLength, out int fieldDef) => throw new NotImplementedException(); int IMetadataImport.FindMemberRef(int typeDef, string name, byte* signature, int signatureLength, out int memberRef) => throw new NotImplementedException(); int IMetadataImport.GetMemberRefProps(int memberRef, int* declaringType, char* name, int nameBufferLength, int* nameLength, byte** signature, int* signatureLength) => throw new NotImplementedException(); int IMetadataImport.EnumProperties(ref void* enumHandle, int typeDef, int* properties, int bufferLength, int* count) => throw new NotImplementedException(); uint IMetadataImport.EnumEvents(ref void* enumHandle, int typeDef, int* events, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetEventProps(int @event, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, int* eventType, int* adderMethodDef, int* removerMethodDef, int* raiserMethodDef, int* otherMethodDefs, int otherMethodDefBufferLength, int* methodMethodDefsLength) => throw new NotImplementedException(); int IMetadataImport.EnumMethodSemantics(ref void* enumHandle, int methodDef, int* eventsAndProperties, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetMethodSemantics(int methodDef, int eventOrProperty, int* semantics) => throw new NotImplementedException(); int IMetadataImport.GetClassLayout(int typeDef, int* packSize, MetadataImportFieldOffset* fieldOffsets, int bufferLength, int* count, int* typeSize) => throw new NotImplementedException(); int IMetadataImport.GetFieldMarshal(int fieldDef, byte** nativeTypeSignature, int* nativeTypeSignatureLengvth) => throw new NotImplementedException(); int IMetadataImport.GetRVA(int methodDef, int* relativeVirtualAddress, int* implAttributes) => throw new NotImplementedException(); int IMetadataImport.GetPermissionSetProps(int declSecurity, uint* action, byte** permissionBlob, int* permissionBlobLength) => throw new NotImplementedException(); int IMetadataImport.GetModuleRefProps(int moduleRef, char* name, int nameBufferLength, int* nameLength) => throw new NotImplementedException(); int IMetadataImport.EnumModuleRefs(ref void* enumHandle, int* moduleRefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetTypeSpecFromToken(int typeSpec, byte** signature, int* signatureLength) => throw new NotImplementedException(); int IMetadataImport.GetNameFromToken(int token, byte* nameUTF8) => throw new NotImplementedException(); int IMetadataImport.EnumUnresolvedMethods(ref void* enumHandle, int* methodDefs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetUserString(int userStringToken, char* buffer, int bufferLength, int* length) => throw new NotImplementedException(); int IMetadataImport.GetPinvokeMap(int memberDef, int* attributes, char* importName, int importNameBufferLength, int* importNameLength, int* moduleRef) => throw new NotImplementedException(); int IMetadataImport.EnumSignatures(ref void* enumHandle, int* signatureTokens, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumTypeSpecs(ref void* enumHandle, int* typeSpecs, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.EnumUserStrings(ref void* enumHandle, int* userStrings, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetParamForMethodIndex(int methodDef, int sequenceNumber, out int parameterToken) => throw new NotImplementedException(); int IMetadataImport.EnumCustomAttributes(ref void* enumHandle, int parent, int attributeType, int* customAttributes, int bufferLength, int* count) => throw new NotImplementedException(); int IMetadataImport.GetCustomAttributeProps(int customAttribute, int* parent, int* constructor, byte** value, int* valueLength) => throw new NotImplementedException(); int IMetadataImport.FindTypeRef(int resolutionScope, string name, out int typeRef) => throw new NotImplementedException(); int IMetadataImport.GetMemberProps(int member, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* relativeVirtualAddress, int* implAttributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetFieldProps(int fieldDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetPropertyProps(int propertyDef, int* declaringTypeDef, char* name, int nameBufferLength, int* nameLength, int* attributes, byte** signature, int* signatureLength, int* constantType, byte** constantValue, int* constantValueLength, int* setterMethodDef, int* getterMethodDef, int* outerMethodDefs, int outerMethodDefsBufferLength, int* otherMethodDefCount) => throw new NotImplementedException(); int IMetadataImport.GetParamProps(int parameter, int* declaringMethodDef, int* sequenceNumber, char* name, int nameBufferLength, int* nameLength, int* attributes, int* constantType, byte** constantValue, int* constantValueLength) => throw new NotImplementedException(); int IMetadataImport.GetCustomAttributeByName(int parent, string name, byte** value, int* valueLength) => throw new NotImplementedException(); bool IMetadataImport.IsValidToken(int token) => throw new NotImplementedException(); int IMetadataImport.GetNativeCallConvFromSig(byte* signature, int signatureLength, int* callingConvention) => throw new NotImplementedException(); int IMetadataImport.IsGlobal(int token, bool value) => throw new NotImplementedException(); void IMetadataEmit.__SetModuleProps() => throw new NotImplementedException(); void IMetadataEmit.__Save() => throw new NotImplementedException(); void IMetadataEmit.__SaveToStream() => throw new NotImplementedException(); void IMetadataEmit.__GetSaveSize() => throw new NotImplementedException(); void IMetadataEmit.__DefineTypeDef() => throw new NotImplementedException(); void IMetadataEmit.__DefineNestedType() => throw new NotImplementedException(); void IMetadataEmit.__SetHandler() => throw new NotImplementedException(); void IMetadataEmit.__DefineMethod() => throw new NotImplementedException(); void IMetadataEmit.__DefineMethodImpl() => throw new NotImplementedException(); void IMetadataEmit.__DefineTypeRefByName() => throw new NotImplementedException(); void IMetadataEmit.__DefineImportType() => throw new NotImplementedException(); void IMetadataEmit.__DefineMemberRef() => throw new NotImplementedException(); void IMetadataEmit.__DefineImportMember() => throw new NotImplementedException(); void IMetadataEmit.__DefineEvent() => throw new NotImplementedException(); void IMetadataEmit.__SetClassLayout() => throw new NotImplementedException(); void IMetadataEmit.__DeleteClassLayout() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldMarshal() => throw new NotImplementedException(); void IMetadataEmit.__DeleteFieldMarshal() => throw new NotImplementedException(); void IMetadataEmit.__DefinePermissionSet() => throw new NotImplementedException(); void IMetadataEmit.__SetRVA() => throw new NotImplementedException(); void IMetadataEmit.__DefineModuleRef() => throw new NotImplementedException(); void IMetadataEmit.__SetParent() => throw new NotImplementedException(); void IMetadataEmit.__GetTokenFromTypeSpec() => throw new NotImplementedException(); void IMetadataEmit.__SaveToMemory() => throw new NotImplementedException(); void IMetadataEmit.__DefineUserString() => throw new NotImplementedException(); void IMetadataEmit.__DeleteToken() => throw new NotImplementedException(); void IMetadataEmit.__SetMethodProps() => throw new NotImplementedException(); void IMetadataEmit.__SetTypeDefProps() => throw new NotImplementedException(); void IMetadataEmit.__SetEventProps() => throw new NotImplementedException(); void IMetadataEmit.__SetPermissionSetProps() => throw new NotImplementedException(); void IMetadataEmit.__DefinePinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__SetPinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__DeletePinvokeMap() => throw new NotImplementedException(); void IMetadataEmit.__DefineCustomAttribute() => throw new NotImplementedException(); void IMetadataEmit.__SetCustomAttributeValue() => throw new NotImplementedException(); void IMetadataEmit.__DefineField() => throw new NotImplementedException(); void IMetadataEmit.__DefineProperty() => throw new NotImplementedException(); void IMetadataEmit.__DefineParam() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldProps() => throw new NotImplementedException(); void IMetadataEmit.__SetPropertyProps() => throw new NotImplementedException(); void IMetadataEmit.__SetParamProps() => throw new NotImplementedException(); void IMetadataEmit.__DefineSecurityAttributeSet() => throw new NotImplementedException(); void IMetadataEmit.__ApplyEditAndContinue() => throw new NotImplementedException(); void IMetadataEmit.__TranslateSigWithScope() => throw new NotImplementedException(); void IMetadataEmit.__SetMethodImplFlags() => throw new NotImplementedException(); void IMetadataEmit.__SetFieldRVA() => throw new NotImplementedException(); void IMetadataEmit.__Merge() => throw new NotImplementedException(); void IMetadataEmit.__MergeEnd() => throw new NotImplementedException(); } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Workspaces/Core/Portable/SemanticModelReuse/AbstractSemanticModelReuseLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal abstract class AbstractSemanticModelReuseLanguageService< TMemberDeclarationSyntax, TBaseMethodDeclarationSyntax, TBasePropertyDeclarationSyntax, TAccessorDeclarationSyntax> : ISemanticModelReuseLanguageService where TMemberDeclarationSyntax : SyntaxNode where TBaseMethodDeclarationSyntax : TMemberDeclarationSyntax where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { /// <summary> /// Used to make sure we only report one watson per sessoin here. /// </summary> private static bool s_watsonReported; protected abstract ISyntaxFacts SyntaxFacts { get; } public abstract SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); protected abstract Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken); protected abstract SyntaxList<TAccessorDeclarationSyntax> GetAccessors(TBasePropertyDeclarationSyntax baseProperty); protected abstract TBasePropertyDeclarationSyntax GetBasePropertyDeclaration(TAccessorDeclarationSyntax accessor); public async Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousSyntaxTree = previousSemanticModel.SyntaxTree; var currentSyntaxTree = currentBodyNode.SyntaxTree; // This operation is only valid if top-level equivalent trees were passed in. If they're not equivalent // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was // still the same. So somehow w don't have top-level equivalence, but we do have the same semantic version. // // log a NFW to help diagnose what the source looks like as it may help us determine what sort of edit is // causing this. if (!previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)) { if (!s_watsonReported) { s_watsonReported = true; try { throw new InvalidOperationException( $@"Syntax trees should have been equivalent. --- {previousSyntaxTree.GetText(CancellationToken.None)} --- {currentSyntaxTree.GetText(CancellationToken.None)} ---"); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } return null; } return await TryGetSpeculativeSemanticModelWorkerAsync( previousSemanticModel, currentBodyNode, cancellationToken).ConfigureAwait(false); } protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) { if (currentBodyNode is TAccessorDeclarationSyntax currentAccessor) { // in the case of an accessor, have to find the previous accessor in the previous prop/event corresponding // to the current prop/event. var currentContainer = GetBasePropertyDeclaration(currentAccessor); var previousContainer = GetPreviousBodyNode(previousRoot, currentRoot, currentContainer); if (previousContainer is not TBasePropertyDeclarationSyntax previousMember) { Debug.Fail("Previous container didn't map back to a normal accessor container."); return null; } var currentAccessors = GetAccessors(currentContainer); var previousAccessors = GetAccessors(previousMember); if (currentAccessors.Count != previousAccessors.Count) { Debug.Fail("Accessor count shouldn't have changed as there were no top level edits."); return null; } return previousAccessors[currentAccessors.IndexOf(currentAccessor)]; } else { var currentMembers = this.SyntaxFacts.GetMethodLevelMembers(currentRoot); var index = currentMembers.IndexOf(currentBodyNode); if (index < 0) { Debug.Fail($"Unhandled member type in {nameof(GetPreviousBodyNode)}"); return null; } var previousMembers = this.SyntaxFacts.GetMethodLevelMembers(previousRoot); if (currentMembers.Count != previousMembers.Count) { Debug.Fail("Member count shouldn't have changed as there were no top level edits."); return null; } return previousMembers[index]; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { internal abstract class AbstractSemanticModelReuseLanguageService< TMemberDeclarationSyntax, TBaseMethodDeclarationSyntax, TBasePropertyDeclarationSyntax, TAccessorDeclarationSyntax> : ISemanticModelReuseLanguageService where TMemberDeclarationSyntax : SyntaxNode where TBaseMethodDeclarationSyntax : TMemberDeclarationSyntax where TBasePropertyDeclarationSyntax : TMemberDeclarationSyntax where TAccessorDeclarationSyntax : SyntaxNode { /// <summary> /// Used to make sure we only report one watson per sessoin here. /// </summary> private static bool s_watsonReported; protected abstract ISyntaxFacts SyntaxFacts { get; } public abstract SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); protected abstract Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken); protected abstract SyntaxList<TAccessorDeclarationSyntax> GetAccessors(TBasePropertyDeclarationSyntax baseProperty); protected abstract TBasePropertyDeclarationSyntax GetBasePropertyDeclaration(TAccessorDeclarationSyntax accessor); public async Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousSyntaxTree = previousSemanticModel.SyntaxTree; var currentSyntaxTree = currentBodyNode.SyntaxTree; // This operation is only valid if top-level equivalent trees were passed in. If they're not equivalent // then something very bad happened as we did that document.Project.GetDependentSemanticVersionAsync was // still the same. So somehow w don't have top-level equivalence, but we do have the same semantic version. // // log a NFW to help diagnose what the source looks like as it may help us determine what sort of edit is // causing this. if (!previousSyntaxTree.IsEquivalentTo(currentSyntaxTree, topLevel: true)) { if (!s_watsonReported) { s_watsonReported = true; try { throw new InvalidOperationException( $@"Syntax trees should have been equivalent. --- {previousSyntaxTree.GetText(CancellationToken.None)} --- {currentSyntaxTree.GetText(CancellationToken.None)} ---"); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } return null; } return await TryGetSpeculativeSemanticModelWorkerAsync( previousSemanticModel, currentBodyNode, cancellationToken).ConfigureAwait(false); } protected SyntaxNode GetPreviousBodyNode(SyntaxNode previousRoot, SyntaxNode currentRoot, SyntaxNode currentBodyNode) { if (currentBodyNode is TAccessorDeclarationSyntax currentAccessor) { // in the case of an accessor, have to find the previous accessor in the previous prop/event corresponding // to the current prop/event. var currentContainer = GetBasePropertyDeclaration(currentAccessor); var previousContainer = GetPreviousBodyNode(previousRoot, currentRoot, currentContainer); if (previousContainer is not TBasePropertyDeclarationSyntax previousMember) { Debug.Fail("Previous container didn't map back to a normal accessor container."); return null; } var currentAccessors = GetAccessors(currentContainer); var previousAccessors = GetAccessors(previousMember); if (currentAccessors.Count != previousAccessors.Count) { Debug.Fail("Accessor count shouldn't have changed as there were no top level edits."); return null; } return previousAccessors[currentAccessors.IndexOf(currentAccessor)]; } else { var currentMembers = this.SyntaxFacts.GetMethodLevelMembers(currentRoot); var index = currentMembers.IndexOf(currentBodyNode); if (index < 0) { Debug.Fail($"Unhandled member type in {nameof(GetPreviousBodyNode)}"); return null; } var previousMembers = this.SyntaxFacts.GetMethodLevelMembers(previousRoot); if (currentMembers.Count != previousMembers.Count) { Debug.Fail("Member count shouldn't have changed as there were no top level edits."); return null; } return previousMembers[index]; } } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/VisualStudio/Core/Def/EditorConfigSettings/Whitespace/View/ColumnDefnitions/WhitespaceDescriptionColumnDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Description)] internal class WhitespaceDescriptionColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceDescriptionColumnDefinition() { } public override string Name => Description; public override string DisplayName => ServicesVSResources.Description; public override bool IsFilterable => false; public override bool IsSortable => false; public override double DefaultWidth => 350; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Whitespace; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View.ColumnDefnitions { [Export(typeof(ITableColumnDefinition))] [Name(Description)] internal class WhitespaceDescriptionColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WhitespaceDescriptionColumnDefinition() { } public override string Name => Description; public override string DisplayName => ServicesVSResources.Description; public override bool IsFilterable => false; public override bool IsSortable => false; public override double DefaultWidth => 350; } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/Extension/Properties/launchSettings.json
{ "profiles": { "Visual Studio Extension": { "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log" } } }
{ "profiles": { "Visual Studio Extension": { "executablePath": "$(DevEnvDir)devenv.exe", "commandLineArgs": "/rootsuffix $(VSSDKTargetPlatformRegRootSuffix) /log" } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicFileBannerFactsService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices <ExportLanguageService(GetType(IFileBannerFactsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFileBannerFactsService Inherits VisualBasicFileBannerFacts Implements IFileBannerFactsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() 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.Composition Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices <ExportLanguageService(GetType(IFileBannerFactsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicFileBannerFactsService Inherits VisualBasicFileBannerFacts Implements IFileBannerFactsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub End Class End Namespace
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/EditorFeatures/VisualBasicTest/Recommendations/OptionStatements/StrictOptionsRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements Public Class StrictOptionsRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionsAfterOptionStrictTest() VerifyRecommendationsAreExactly(<File>Option Strict |</File>, "On", "Off") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements Public Class StrictOptionsRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OptionsAfterOptionStrictTest() VerifyRecommendationsAreExactly(<File>Option Strict |</File>, "On", "Off") End Sub End Class End Namespace
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.DoubleTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct DoubleTC : FloatingTC<double>, INumericTC<double> { double INumericTC<double>.MinValue => double.NegativeInfinity; double INumericTC<double>.MaxValue => double.PositiveInfinity; double FloatingTC<double>.NaN => double.NaN; double INumericTC<double>.Zero => 0.0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public double Next(double value) { Debug.Assert(!double.IsNaN(value)); Debug.Assert(value != double.PositiveInfinity); if (value == 0) return double.Epsilon; if (value < 0) { if (value == -double.Epsilon) return 0.0; // skip negative zero if (value == double.NegativeInfinity) return double.MinValue; return -ULongAsDouble(DoubleAsULong(-value) - 1); } if (value == double.MaxValue) return double.PositiveInfinity; return ULongAsDouble(DoubleAsULong(value) + 1); } private static ulong DoubleAsULong(double d) { if (d == 0) return 0; return (ulong)BitConverter.DoubleToInt64Bits(d); } private static double ULongAsDouble(ulong l) { return BitConverter.Int64BitsToDouble((long)l); } bool INumericTC<double>.Related(BinaryOperatorKind relation, double left, double right) { switch (relation) { case Equal: return left == right || double.IsNaN(left) && double.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } double INumericTC<double>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0 : constantValue.DoubleValue; ConstantValue INumericTC<double>.ToConstantValue(double value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<double>.ToString(double value) => double.IsNaN(value) ? "NaN" : value == double.NegativeInfinity ? "-Inf" : value == double.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G17}"); double INumericTC<double>.Prev(double value) { return -Next(-value); } double INumericTC<double>.Random(Random random) { return random.NextDouble() * 100 - 50; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct DoubleTC : FloatingTC<double>, INumericTC<double> { double INumericTC<double>.MinValue => double.NegativeInfinity; double INumericTC<double>.MaxValue => double.PositiveInfinity; double FloatingTC<double>.NaN => double.NaN; double INumericTC<double>.Zero => 0.0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public double Next(double value) { Debug.Assert(!double.IsNaN(value)); Debug.Assert(value != double.PositiveInfinity); if (value == 0) return double.Epsilon; if (value < 0) { if (value == -double.Epsilon) return 0.0; // skip negative zero if (value == double.NegativeInfinity) return double.MinValue; return -ULongAsDouble(DoubleAsULong(-value) - 1); } if (value == double.MaxValue) return double.PositiveInfinity; return ULongAsDouble(DoubleAsULong(value) + 1); } private static ulong DoubleAsULong(double d) { if (d == 0) return 0; return (ulong)BitConverter.DoubleToInt64Bits(d); } private static double ULongAsDouble(ulong l) { return BitConverter.Int64BitsToDouble((long)l); } bool INumericTC<double>.Related(BinaryOperatorKind relation, double left, double right) { switch (relation) { case Equal: return left == right || double.IsNaN(left) && double.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } double INumericTC<double>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0 : constantValue.DoubleValue; ConstantValue INumericTC<double>.ToConstantValue(double value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<double>.ToString(double value) => double.IsNaN(value) ? "NaN" : value == double.NegativeInfinity ? "-Inf" : value == double.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G17}"); double INumericTC<double>.Prev(double value) { return -Next(-value); } double INumericTC<double>.Random(Random random) { return random.NextDouble() * 100 - 50; } } } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.zh-Hant.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="zh-Hant" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# 互動</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="zh-Hant" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# 互動</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.GenerateNamedType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { private partial class Editor { private async Task<INamedTypeSymbol> GenerateNamedTypeAsync() { return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), DetermineAccessibility(), DetermineModifiers(), DetermineTypeKind(), DetermineName(), DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: await DetermineMembersAsync().ConfigureAwait(false)); } private async Task<INamedTypeSymbol> GenerateNamedTypeAsync(GenerateTypeOptionsResult options) { if (options.TypeKind == TypeKind.Delegate) { return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), DetermineReturnType(), RefKind.None, name: options.TypeName, typeParameters: DetermineTypeParametersWithDelegateChecks(), parameters: DetermineParameters()); } return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), options.TypeKind, options.TypeName, DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: await DetermineMembersAsync(options).ConfigureAwait(false)); } private ITypeSymbol DetermineReturnType() { if (_state.DelegateMethodSymbol == null || _state.DelegateMethodSymbol.ReturnType == null || _state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol) { // Since we cannot determine the return type, we are returning void return _state.Compilation.GetSpecialType(SpecialType.System_Void); } else { return _state.DelegateMethodSymbol.ReturnType; } } private ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWithDelegateChecks() { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.TypeParameters; } // If the delegate symbol cannot be determined then return DetermineTypeParameters(); } private ImmutableArray<IParameterSymbol> DetermineParameters() { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.Parameters; } return default; } private async Task<ImmutableArray<ISymbol>> DetermineMembersAsync(GenerateTypeOptionsResult options = null) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members); await AddMembersAsync(members, options).ConfigureAwait(false); if (_state.IsException) AddExceptionConstructors(members); return members.ToImmutable(); } private async Task AddMembersAsync(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { AddProperties(members); if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList)) { return; } var parameterTypes = GetArgumentTypes(argumentList); // Don't generate this constructor if it would conflict with a default exception // constructor. Default exception constructors will be added automatically by our // caller. if (_state.IsException && _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any( c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes, SymbolEqualityComparer.Default))) { return; } // If there's an accessible base constructor that would accept these types, then // just call into that instead of generating fields. if (_state.BaseTypeOrInterfaceOpt != null) { if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface || argumentList.Count == 0) { // No need to add the default constructor if our base type is going to be 'object' or if we // would be calling the empty constructor. We get that base constructor implicitly. return; } // Synthesize some parameter symbols so we can see if these particular parameters could map to the // parameters of any of the constructors we have in our base class. This will have the added // benefit of allowing us to infer better types for complex type-less expressions (like lambdas). var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var refKinds = argumentList.SelectAsArray(a => syntaxFacts.GetRefKindOfArgument(a)); var parameters = parameterTypes.Zip(refKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = GetArgumentExpressions(argumentList); var delegatedConstructor = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.FirstOrDefault( c => GenerateConstructorHelpers.CanDelegateTo(_semanticDocument, parameters, expressions, c)); if (delegatedConstructor != null) { // There was a constructor match in the base class. Synthesize a constructor of our own with // the same parameter types that calls into that. var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); members.Add(factory.CreateBaseDelegatingConstructor(delegatedConstructor, DetermineName())); return; } } // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. await AddFieldDelegatingConstructorAsync(argumentList, members, options).ConfigureAwait(false); } private void AddProperties(ArrayBuilder<ISymbol> members) { var typeInference = _semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); foreach (var property in _state.PropertiesToGenerate) { if (_service.TryGenerateProperty(property, _semanticDocument.SemanticModel, typeInference, _cancellationToken, out var generatedProperty)) { members.Add(generatedProperty); } } } private async Task AddFieldDelegatingConstructorAsync( IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken); var parameterTypes = GetArgumentTypes(argumentList); var parameterNames = _service.GenerateParameterNames(_semanticDocument.SemanticModel, argumentList, _cancellationToken); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); for (var i = 0; i < parameterNames.Count; i++) { var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]); var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; parameterType = parameterType.RemoveUnavailableTypeParameters( _semanticDocument.SemanticModel.Compilation, availableTypeParameters); await FindExistingOrCreateNewMemberAsync(parameterName, parameterType, parameterToExistingFieldMap, parameterToNewFieldMap).ConfigureAwait(false); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: refKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } // Empty Constructor for Struct is not allowed if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure))) { members.AddRange(factory.CreateMemberDelegatingConstructor( _semanticDocument.SemanticModel, DetermineName(), null, parameters.ToImmutable(), parameterToExistingFieldMap.ToImmutable(), parameterToNewFieldMap.ToImmutable(), addNullChecks: false, preferThrowExpression: false, generateProperties: false, isContainedInUnsafeType: false)); // Since we generated the type, we know its not unsafe } } private void AddExceptionConstructors(ArrayBuilder<ISymbol> members) { var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var exceptionType = _semanticDocument.SemanticModel.Compilation.ExceptionType(); var constructors = exceptionType.InstanceConstructors .Where(c => c.DeclaredAccessibility is Accessibility.Public or Accessibility.Protected) .Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: c.DeclaredAccessibility, modifiers: default, typeName: DetermineName(), parameters: c.Parameters, statements: default, baseConstructorArguments: c.Parameters.Length == 0 ? default : factory.CreateArguments(c.Parameters))); members.AddRange(constructors); } private ImmutableArray<AttributeData> DetermineAttributes() { if (_state.IsException) { var serializableType = _semanticDocument.SemanticModel.Compilation.SerializableAttributeType(); if (serializableType != null) { var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType); return ImmutableArray.Create(attribute); } } return default; } private Accessibility DetermineAccessibility() => _service.GetAccessibility(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken); private static DeclarationModifiers DetermineModifiers() => default; private INamedTypeSymbol DetermineBaseType() { if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { return null; } return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); } private ImmutableArray<INamedTypeSymbol> DetermineInterfaces() { if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); if (type != null) { return ImmutableArray.Create(type); } } return ImmutableArray<INamedTypeSymbol>.Empty; } private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type) { return type.RemoveUnavailableTypeParameters( _semanticDocument.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol; } private string DetermineName() => GetTypeName(_state); private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters() => _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken); private TypeKind DetermineTypeKind() { return _state.IsStruct ? TypeKind.Struct : _state.IsInterface ? TypeKind.Interface : TypeKind.Class; } protected IList<ITypeParameterSymbol> GetAvailableTypeParameters() { var availableInnerTypeParameters = _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken); var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null ? _state.TypeToGenerateInOpt.GetAllTypeParameters() : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList(); } } internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { private partial class Editor { private async Task<INamedTypeSymbol> GenerateNamedTypeAsync() { return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), DetermineAccessibility(), DetermineModifiers(), DetermineTypeKind(), DetermineName(), DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: await DetermineMembersAsync().ConfigureAwait(false)); } private async Task<INamedTypeSymbol> GenerateNamedTypeAsync(GenerateTypeOptionsResult options) { if (options.TypeKind == TypeKind.Delegate) { return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), DetermineReturnType(), RefKind.None, name: options.TypeName, typeParameters: DetermineTypeParametersWithDelegateChecks(), parameters: DetermineParameters()); } return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), options.TypeKind, options.TypeName, DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: await DetermineMembersAsync(options).ConfigureAwait(false)); } private ITypeSymbol DetermineReturnType() { if (_state.DelegateMethodSymbol == null || _state.DelegateMethodSymbol.ReturnType == null || _state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol) { // Since we cannot determine the return type, we are returning void return _state.Compilation.GetSpecialType(SpecialType.System_Void); } else { return _state.DelegateMethodSymbol.ReturnType; } } private ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWithDelegateChecks() { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.TypeParameters; } // If the delegate symbol cannot be determined then return DetermineTypeParameters(); } private ImmutableArray<IParameterSymbol> DetermineParameters() { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.Parameters; } return default; } private async Task<ImmutableArray<ISymbol>> DetermineMembersAsync(GenerateTypeOptionsResult options = null) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members); await AddMembersAsync(members, options).ConfigureAwait(false); if (_state.IsException) AddExceptionConstructors(members); return members.ToImmutable(); } private async Task AddMembersAsync(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { AddProperties(members); if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList)) { return; } var parameterTypes = GetArgumentTypes(argumentList); // Don't generate this constructor if it would conflict with a default exception // constructor. Default exception constructors will be added automatically by our // caller. if (_state.IsException && _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any( c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes, SymbolEqualityComparer.Default))) { return; } // If there's an accessible base constructor that would accept these types, then // just call into that instead of generating fields. if (_state.BaseTypeOrInterfaceOpt != null) { if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface || argumentList.Count == 0) { // No need to add the default constructor if our base type is going to be 'object' or if we // would be calling the empty constructor. We get that base constructor implicitly. return; } // Synthesize some parameter symbols so we can see if these particular parameters could map to the // parameters of any of the constructors we have in our base class. This will have the added // benefit of allowing us to infer better types for complex type-less expressions (like lambdas). var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var refKinds = argumentList.SelectAsArray(a => syntaxFacts.GetRefKindOfArgument(a)); var parameters = parameterTypes.Zip(refKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = GetArgumentExpressions(argumentList); var delegatedConstructor = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.FirstOrDefault( c => GenerateConstructorHelpers.CanDelegateTo(_semanticDocument, parameters, expressions, c)); if (delegatedConstructor != null) { // There was a constructor match in the base class. Synthesize a constructor of our own with // the same parameter types that calls into that. var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); members.Add(factory.CreateBaseDelegatingConstructor(delegatedConstructor, DetermineName())); return; } } // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. await AddFieldDelegatingConstructorAsync(argumentList, members, options).ConfigureAwait(false); } private void AddProperties(ArrayBuilder<ISymbol> members) { var typeInference = _semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); foreach (var property in _state.PropertiesToGenerate) { if (_service.TryGenerateProperty(property, _semanticDocument.SemanticModel, typeInference, _cancellationToken, out var generatedProperty)) { members.Add(generatedProperty); } } } private async Task AddFieldDelegatingConstructorAsync( IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken); var parameterTypes = GetArgumentTypes(argumentList); var parameterNames = _service.GenerateParameterNames(_semanticDocument.SemanticModel, argumentList, _cancellationToken); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); for (var i = 0; i < parameterNames.Count; i++) { var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]); var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; parameterType = parameterType.RemoveUnavailableTypeParameters( _semanticDocument.SemanticModel.Compilation, availableTypeParameters); await FindExistingOrCreateNewMemberAsync(parameterName, parameterType, parameterToExistingFieldMap, parameterToNewFieldMap).ConfigureAwait(false); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: refKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } // Empty Constructor for Struct is not allowed if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure))) { members.AddRange(factory.CreateMemberDelegatingConstructor( _semanticDocument.SemanticModel, DetermineName(), null, parameters.ToImmutable(), parameterToExistingFieldMap.ToImmutable(), parameterToNewFieldMap.ToImmutable(), addNullChecks: false, preferThrowExpression: false, generateProperties: false, isContainedInUnsafeType: false)); // Since we generated the type, we know its not unsafe } } private void AddExceptionConstructors(ArrayBuilder<ISymbol> members) { var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var exceptionType = _semanticDocument.SemanticModel.Compilation.ExceptionType(); var constructors = exceptionType.InstanceConstructors .Where(c => c.DeclaredAccessibility is Accessibility.Public or Accessibility.Protected) .Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: c.DeclaredAccessibility, modifiers: default, typeName: DetermineName(), parameters: c.Parameters, statements: default, baseConstructorArguments: c.Parameters.Length == 0 ? default : factory.CreateArguments(c.Parameters))); members.AddRange(constructors); } private ImmutableArray<AttributeData> DetermineAttributes() { if (_state.IsException) { var serializableType = _semanticDocument.SemanticModel.Compilation.SerializableAttributeType(); if (serializableType != null) { var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType); return ImmutableArray.Create(attribute); } } return default; } private Accessibility DetermineAccessibility() => _service.GetAccessibility(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken); private static DeclarationModifiers DetermineModifiers() => default; private INamedTypeSymbol DetermineBaseType() { if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { return null; } return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); } private ImmutableArray<INamedTypeSymbol> DetermineInterfaces() { if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); if (type != null) { return ImmutableArray.Create(type); } } return ImmutableArray<INamedTypeSymbol>.Empty; } private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type) { return type.RemoveUnavailableTypeParameters( _semanticDocument.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol; } private string DetermineName() => GetTypeName(_state); private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters() => _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken); private TypeKind DetermineTypeKind() { return _state.IsStruct ? TypeKind.Struct : _state.IsInterface ? TypeKind.Interface : TypeKind.Class; } protected IList<ITypeParameterSymbol> GetAvailableTypeParameters() { var availableInnerTypeParameters = _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken); var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null ? _state.TypeToGenerateInOpt.GetAllTypeParameters() : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList(); } } internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property); } }
-1
dotnet/roslyn
56,484
Fix features using ISyntaxFacts as a place to store C# specific questions
CyrusNajmabadi
"2021-09-17T17:20:18Z"
"2021-09-17T18:54:11Z"
d695369176aa109f0e0fb8b0019294aaa0823a54
7fb0d236cdda24e8003f60c0fd32fc2af215027c
Fix features using ISyntaxFacts as a place to store C# specific questions.
./src/Features/LanguageServer/Protocol/ProtocolConstants.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.LanguageServer { internal class ProtocolConstants { public const string RazorCSharp = "RazorCSharp"; public static ImmutableArray<string> RoslynLspLanguages = ImmutableArray.Create(LanguageNames.CSharp, LanguageNames.VisualBasic, LanguageNames.FSharp); } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.LanguageServer { internal class ProtocolConstants { public const string RazorCSharp = "RazorCSharp"; public static ImmutableArray<string> RoslynLspLanguages = ImmutableArray.Create(LanguageNames.CSharp, LanguageNames.VisualBasic, LanguageNames.FSharp); } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./docs/contributing/Building, Debugging, and Testing on Unix.md
# Building, Debugging and Testing on Unix This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux. Particularly for developers who aren't experienced with .NET Core development on Linux. ## Working with the code 1. Ensure the commands `git` and `curl` are available 1. Clone git@github.com:dotnet/roslyn.git 1. Run `./build.sh --restore` 1. Run `./build.sh --build` ## Working in Visual Studio Code 1. Install [VS Code](https://code.visualstudio.com/Download) - After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) - Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*. 2. Install a recent preview [.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core). At time of writing, Roslyn uses .NET 5 preview 8. The exact version in use is recorded in our [global.json](https://github.com/dotnet/roslyn/blob/main/global.json) file. 3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor). 4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*). ## Running Tests The unit tests can be executed by running `./build.sh --test`. To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command. ## GitHub The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for getting this setup. https://help.github.com/articles/connecting-to-github-with-ssh/ ## Debugging test failures The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar with it then lldb debugging will be pretty straight forward. The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information: - [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md) - [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md) - [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md) CoreCLR also has some guidelines for specific Linux debugging scenarios: - https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md - https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb. Corrections: - LLDB and createdump must be run as root - `dotnet tool install -g dotnet-symbol` must be run from `$HOME` ### Core Dumps The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via environment variables that you want a core dump to be produced. The simplest setup is to do the following: ``` > export COMPlus_DbgEnableMiniDump=1 > export COMPlus_DbgMiniDumpType=4 ``` This will cause full memory dumps to be produced which can then be loaded into LLDB. A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps. ### GC stress failures When you suspect there is a GC failure related to your test then you can use the following environment variables to help track it down. ``` > export COMPlus_HeapVerify=1 > export COMPlus_gcConcurrent=1 ``` The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with a more actionable trace for the GC team. The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is indeed crashing in the GC. Note: this variables can also be used on Windows as well. ## Ubuntu 18.04 The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V. This makes it easier to use from a Windows machine: full screen, copy / paste, etc ... ### Hyper-V Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating such an image: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine When following this make sure to: 1. Click Installation Source and uncheck "Windows Secure Boot" 1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done. Overall this takes about 5-10 minutes to complete. ### Source Link Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes. To disable source link add the following to the `Directory.Build.props` file in the root of the repository. ``` xml <EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries> <EnableSourceLink>false</EnableSourceLink> <DeterministicSourcePaths>false</DeterministicSourcePaths> ``` ### Prerequisites Make sure to install the following via `apt install` - clang - lldb - cmake - xrdp
# Building, Debugging and Testing on Unix This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux. Particularly for developers who aren't experienced with .NET Core development on Linux. ## Working with the code 1. Ensure the commands `git` and `curl` are available 1. Clone git@github.com:dotnet/roslyn.git 1. Run `./build.sh --restore` 1. Run `./build.sh --build` ## Working in Visual Studio Code 1. Install [VS Code](https://code.visualstudio.com/Download) - After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) - Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*. 2. Install the [.NET 6.0 RC 1 SDK](https://dotnet.microsoft.com/download/dotnet-core/6.0). 3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor). 4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*). ## Running Tests The unit tests can be executed by running `./build.sh --test`. To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command. ## GitHub The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for getting this setup. https://help.github.com/articles/connecting-to-github-with-ssh/ ## Debugging test failures The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar with it then lldb debugging will be pretty straight forward. The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information: - [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md) - [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md) - [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md) CoreCLR also has some guidelines for specific Linux debugging scenarios: - https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md - https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb. Corrections: - LLDB and createdump must be run as root - `dotnet tool install -g dotnet-symbol` must be run from `$HOME` ### Core Dumps The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via environment variables that you want a core dump to be produced. The simplest setup is to do the following: ``` > export COMPlus_DbgEnableMiniDump=1 > export COMPlus_DbgMiniDumpType=4 ``` This will cause full memory dumps to be produced which can then be loaded into LLDB. A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps. ### GC stress failures When you suspect there is a GC failure related to your test then you can use the following environment variables to help track it down. ``` > export COMPlus_HeapVerify=1 > export COMPlus_gcConcurrent=1 ``` The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with a more actionable trace for the GC team. The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is indeed crashing in the GC. Note: this variables can also be used on Windows as well. ## Ubuntu 18.04 The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V. This makes it easier to use from a Windows machine: full screen, copy / paste, etc ... ### Hyper-V Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating such an image: https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine When following this make sure to: 1. Click Installation Source and uncheck "Windows Secure Boot" 1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done. Overall this takes about 5-10 minutes to complete. ### Source Link Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes. To disable source link add the following to the `Directory.Build.props` file in the root of the repository. ``` xml <EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries> <EnableSourceLink>false</EnableSourceLink> <DeterministicSourcePaths>false</DeterministicSourcePaths> ``` ### Prerequisites Make sure to install the following via `apt install` - clang - lldb - cmake - xrdp
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./docs/contributing/Building, Debugging, and Testing on Windows.md
# Building, Debugging and Testing on Windows ## Working with the code Using the command line, Roslyn can be developed using the following pattern: 1. Clone https://github.com/dotnet/roslyn 1. Run Restore.cmd 1. Run Build.cmd 1. Run Test.cmd ## Recommended version of .NET Framework The minimal required version of .NET Framework is 4.7.2. ## Developing with Visual Studio 2022 1. [Visual Studio 2022 17.0 Preview](https://visualstudio.microsoft.com/vs/preview/vs2022/) - Ensure C#, VB, MSBuild, .NET Core and Visual Studio Extensibility are included in the selected work loads - Ensure Visual Studio is on Version "17.0" or greater - Ensure "Use previews of the .NET Core SDK" is checked in Tools -> Options -> Environment -> Preview Features - Restart Visual Studio 1. [.NET 6.0 Preview 7 SDK](https://dotnet.microsoft.com/download/dotnet-core/6.0) [Windows x64 installer](https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-6.0.100-preview.7-windows-x64-installer) 1. [PowerShell 5.0 or newer](https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell). If you are on Windows 10, you are fine; you'll only need to upgrade if you're on earlier versions of Windows. The download link is under the ["Upgrading existing Windows PowerShell"](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell) heading. 1. Run Restore.cmd 1. Open Roslyn.sln ## Developing with Visual Studio Code See the [Building, Debugging, and Testing on Unix](Building,%20Debugging,%20and%20Testing%20on%20Unix.md#working-in-visual-studio-code) documentation to get started developing Roslyn using Visual Studio Code. ## Running Tests There are a number of options for running the core Roslyn unit tests: ### Command Line The Test.cmd script will run our unit test on already built binaries. It can be passed the `-build` argument to force a new build before running tests. 1. Run the "Developer Command Prompt for VS2022" from your start menu. 2. Navigate to the directory of your Git clone. 3. Run `Test.cmd` in the command prompt. You can more precisely control how the tests are run by running the eng/build.ps1 script directly with the relevant options. For example passing in the `-test` switch will run the tests on .NET Framework, whilst passing in the `-testCoreClr` switch will run the tests on .NET Core. The results of the tests can be viewed in the artifacts/TestResults directory. ### Test Explorer Tests can be run and debugged from the Test Explorer window. For best performance, we recommend the following: 1. Open **Tools &rarr; Options... &rarr; Test** 1. Check the box for **Discover tests in real time from source files** 2. Uncheck the box for **Additionally discover tests from build assemblies...** 2. Use the Search box of Test Explorer to narrow the scope of visible tests to the feature(s) you are working on 3. When you are not actively running tests, set the search query to `__NonExistent__` to hide all tests from the UI ### WPF Test Runner To debug through tests, you can right click the test project that contains your tests and choose **Set as Startup Project**. Then press F5. This will run the tests under the command line runner. Some members of the team have been working on a GUI runner that allows selection of individual tests, etc. Grab the source from [xunit.runner.wpf](https://github.com/pilchie/xunit.runner.wpf), build it and give it a try. ## Trying Your Changes in Visual Studio ### Deploying with F5 The Rosyln solution is designed to support easy debugging via F5. Several of our projects produce VSIX which deploy into Visual Studio during build. The F5 operation will start a new Visual Studio instance using those VSIX which override our installed binaries. This means trying out a change to the language, IDE or debugger is as simple as hitting F5. Note that for changes to the compiler, out-of-process builds won't use the privately built version of the compiler. The startup project needs to be set to `RoslynDeployment`. This should be the default but in some cases will need to be set explicitly. Here are what is deployed with each extension, by project that builds it. If you're working on a particular area, you probably want to set the appropriate project as your startup project to optimize building and deploying only the relevant bits. - **Roslyn.VisualStudio.Setup**: this project can be found inside the VisualStudio folder from the Solution Explorer, and builds Roslyn.VisualStudio.Setup.vsix. It contains the core language services that provide C# and VB editing. It also contains the copy of the compiler that is used to drive IntelliSense and semantic analysis in Visual Studio. Although this is the copy of the compiler that's used to generate squiggles and other information, it's not the compiler used to actually produce your final .exe or .dll when you do a build. If you're working on fixing an IDE bug, this is the project you want to use. - **Roslyn.VisualStudio.InteractiveComponents**: this project can be found in the Interactive\Setup folder from the Solution Explorer, and builds Roslyn.VisualStudio.InteractiveComponents.vsix. - **Roslyn.Compilers.Extension**: this project can be found inside the Compilers\Packages folder from the Solution Explorer, and builds Roslyn.Compilers.Extension.vsix. This deploys a copy of the command line compilers that are used to do actual builds in the IDE. It only affects builds triggered from the Visual Studio experimental instance it's installed into, so it won't affect your regular builds. Note that if you install just this, the IDE won't know about any language features included in your build. If you're regularly working on new language features, you may wish to consider building both the CompilerExtension and VisualStudioSetup projects to ensure the real build and live analysis are synchronized. - **ExpressionEvaluatorPackage**: this project can be found inside the ExpressionEvaluator\Setup folder from the Solution Explorer, and builds ExpressionEvaluatorPackage.vsix. This deploys the expression evaluator and result providers, the components that are used by the debugger to parse and evaluate C# and VB expressions in the Watch window, Immediate window, and more. These components are only used when debugging. The experimental instance used by Roslyn is an entirely separate instance of Visual Studio with it's own settings and installed extensions. It's also, by default, a separate instance than the standard "Experimental Instance" used by other Visual Studio SDK projects. If you're familiar with the idea of Visual Studio hives, we deploy into the RoslynDev root suffix. ### Deploying with VSIX and Nuget package If you want to try your extension in your day-to-day use of Visual Studio, you can find the extensions you built in your Binaries folder with the .vsix extension. You can double-click the extension to install it into your main Visual Studio hive. This will replace the base installed version. Once it's installed, you'll see it marked as "Experimental" in Tools > Extensions and Updates to indicate you're running your experimental version. You can uninstall your version and go back to the originally installed version by choosing your version and clicking Uninstall. If you only install the VSIX, then the IDE will behave correctly (ie. new compiler and IDE behavior), but the Build operation or building from the command-line won't. To fix that, add a reference to the `Microsoft.Net.Compilers.Toolset` you built into your csproj. As shown below, you'll want to (1) add a nuget source pointing to your local build folder, (2) add the package reference, then (3) verify the Build Output of your project with a `#error version` included in your program. ![image](https://user-images.githubusercontent.com/12466233/81205885-25252a80-8f80-11ea-9d75-268c7fe6f3ed.png) ![image](https://user-images.githubusercontent.com/12466233/81205974-4128cc00-8f80-11ea-93ec-641d87662b12.png) ![image](https://user-images.githubusercontent.com/12466233/81206129-7fbe8680-8f80-11ea-9438-acc0481a3585.png) ### Deploying with command-line You can build and deploy with the following command: `.\Build.cmd -Configuration Release -deployExtensions -launch`. Then you can launch the `RoslynDev` hive with `devenv /rootSuffix RoslynDev`. ### Referencing bootstrap compiler If you made changes to a Roslyn compiler and want to build any projects with it, you can either use the Visual Studio hive where your **CompilerExtension** is installed, or from command line, run msbuild with `/p:BootstrapBuildPath=YourBootstrapBuildPath`. `YourBootstrapBuildPath` could be any directory on your machine so long as it had csc and vbc inside it. You can check the cibuild.cmd and see how it is used. ### Troubleshooting your setup To confirm what version of the compiler is being used, include `#error version` in your program and the compiler will produce a diagnostic including its own version as well as the language version it is operating under. You can also attach a debugger to Visual Studio and check the loaded modules, looking at the folder where the various `CodeAnalysis` modules were loaded from (the `RoslynDev` should load them somewhere under `AppData`, not from `Program File`). ### Testing on the [dotnet/runtime](https://github.com/dotnet/runtime) repo 1. make sure that you can build the `runtime` repo as baseline (run `build.cmd libs`, which should be sufficient to build all C# code, installing any prerequisites if prompted to) 2. `build.cmd -pack` on your `roslyn` repo 3. in `%userprofile%\.nuget\packages\microsoft.net.compilers.toolset` delete the version of the toolset that you just packed so that the new one will get put into the cache 4. modify your local enlistment of `runtime` as illustrated in [this commit](https://github.com/RikkiGibson/runtime/commit/da3c6d96c3764e571269b07650a374678b476384) then build again - add `<RestoreAdditionalProjectSources><PATH-TO-YOUR-ROSLYN-ENLISTMENT>\artifacts\packages\Debug\Shipping\</RestoreAdditionalProjectSources>` using the local path to your `roslyn` repo to `Directory.Build.props` - add `<MicrosoftNetCompilersToolsetVersion>3.9.0-dev</MicrosoftNetCompilersToolsetVersion>` with the package version you just packed (look in above artifacts folder) to `eng/Versions.props` ### Testing with extra IOperation validation Run `build.cmd -testIOperation` which sets the `ROSLYN_TEST_IOPERATION` environment variable to `true` and runs the tests. For running those tests in an IDE, the easiest is to find the `//#define ROSLYN_TEST_IOPERATION` directive and uncomment it. See more details in the [IOperation test hook](https://github.com/dotnet/roslyn/blob/main/docs/compilers/IOperation%20Test%20Hook.md) doc. ## Contributing Please see [Contributing Code](https://github.com/dotnet/roslyn/blob/main/CONTRIBUTING.md) for details on contributing changes back to the code.
# Building, Debugging and Testing on Windows ## Working with the code Using the command line, Roslyn can be developed using the following pattern: 1. Clone https://github.com/dotnet/roslyn 1. Run Restore.cmd 1. Run Build.cmd 1. Run Test.cmd ## Recommended version of .NET Framework The minimal required version of .NET Framework is 4.7.2. ## Developing with Visual Studio 2022 1. [Visual Studio 2022 17.0 Preview](https://visualstudio.microsoft.com/vs/preview/vs2022/) - Ensure C#, VB, MSBuild, .NET Core and Visual Studio Extensibility are included in the selected work loads - Ensure Visual Studio is on Version "17.0" or greater - Ensure "Use previews of the .NET Core SDK" is checked in Tools -> Options -> Environment -> Preview Features - Restart Visual Studio 1. [.NET 6.0 RC 1 SDK](https://dotnet.microsoft.com/download/dotnet-core/6.0) [Windows x64 installer](https://dotnet.microsoft.com/download/dotnet/thank-you/sdk-6.0.100-rc.1-windows-x64-installer) 1. [PowerShell 5.0 or newer](https://docs.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell). If you are on Windows 10, you are fine; you'll only need to upgrade if you're on earlier versions of Windows. The download link is under the ["Upgrading existing Windows PowerShell"](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6#upgrading-existing-windows-powershell) heading. 1. Run Restore.cmd 1. Open Roslyn.sln ## Developing with Visual Studio Code See the [Building, Debugging, and Testing on Unix](Building,%20Debugging,%20and%20Testing%20on%20Unix.md#working-in-visual-studio-code) documentation to get started developing Roslyn using Visual Studio Code. ## Running Tests There are a number of options for running the core Roslyn unit tests: ### Command Line The Test.cmd script will run our unit test on already built binaries. It can be passed the `-build` argument to force a new build before running tests. 1. Run the "Developer Command Prompt for VS2022" from your start menu. 2. Navigate to the directory of your Git clone. 3. Run `Test.cmd` in the command prompt. You can more precisely control how the tests are run by running the eng/build.ps1 script directly with the relevant options. For example passing in the `-test` switch will run the tests on .NET Framework, whilst passing in the `-testCoreClr` switch will run the tests on .NET Core. The results of the tests can be viewed in the artifacts/TestResults directory. ### Test Explorer Tests can be run and debugged from the Test Explorer window. For best performance, we recommend the following: 1. Open **Tools &rarr; Options... &rarr; Test** 1. Check the box for **Discover tests in real time from source files** 2. Uncheck the box for **Additionally discover tests from build assemblies...** 2. Use the Search box of Test Explorer to narrow the scope of visible tests to the feature(s) you are working on 3. When you are not actively running tests, set the search query to `__NonExistent__` to hide all tests from the UI ### WPF Test Runner To debug through tests, you can right click the test project that contains your tests and choose **Set as Startup Project**. Then press F5. This will run the tests under the command line runner. Some members of the team have been working on a GUI runner that allows selection of individual tests, etc. Grab the source from [xunit.runner.wpf](https://github.com/pilchie/xunit.runner.wpf), build it and give it a try. ## Trying Your Changes in Visual Studio ### Deploying with F5 The Rosyln solution is designed to support easy debugging via F5. Several of our projects produce VSIX which deploy into Visual Studio during build. The F5 operation will start a new Visual Studio instance using those VSIX which override our installed binaries. This means trying out a change to the language, IDE or debugger is as simple as hitting F5. Note that for changes to the compiler, out-of-process builds won't use the privately built version of the compiler. The startup project needs to be set to `RoslynDeployment`. This should be the default but in some cases will need to be set explicitly. Here are what is deployed with each extension, by project that builds it. If you're working on a particular area, you probably want to set the appropriate project as your startup project to optimize building and deploying only the relevant bits. - **Roslyn.VisualStudio.Setup**: this project can be found inside the VisualStudio folder from the Solution Explorer, and builds Roslyn.VisualStudio.Setup.vsix. It contains the core language services that provide C# and VB editing. It also contains the copy of the compiler that is used to drive IntelliSense and semantic analysis in Visual Studio. Although this is the copy of the compiler that's used to generate squiggles and other information, it's not the compiler used to actually produce your final .exe or .dll when you do a build. If you're working on fixing an IDE bug, this is the project you want to use. - **Roslyn.VisualStudio.InteractiveComponents**: this project can be found in the Interactive\Setup folder from the Solution Explorer, and builds Roslyn.VisualStudio.InteractiveComponents.vsix. - **Roslyn.Compilers.Extension**: this project can be found inside the Compilers\Packages folder from the Solution Explorer, and builds Roslyn.Compilers.Extension.vsix. This deploys a copy of the command line compilers that are used to do actual builds in the IDE. It only affects builds triggered from the Visual Studio experimental instance it's installed into, so it won't affect your regular builds. Note that if you install just this, the IDE won't know about any language features included in your build. If you're regularly working on new language features, you may wish to consider building both the CompilerExtension and VisualStudioSetup projects to ensure the real build and live analysis are synchronized. - **ExpressionEvaluatorPackage**: this project can be found inside the ExpressionEvaluator\Setup folder from the Solution Explorer, and builds ExpressionEvaluatorPackage.vsix. This deploys the expression evaluator and result providers, the components that are used by the debugger to parse and evaluate C# and VB expressions in the Watch window, Immediate window, and more. These components are only used when debugging. The experimental instance used by Roslyn is an entirely separate instance of Visual Studio with it's own settings and installed extensions. It's also, by default, a separate instance than the standard "Experimental Instance" used by other Visual Studio SDK projects. If you're familiar with the idea of Visual Studio hives, we deploy into the RoslynDev root suffix. ### Deploying with VSIX and Nuget package If you want to try your extension in your day-to-day use of Visual Studio, you can find the extensions you built in your Binaries folder with the .vsix extension. You can double-click the extension to install it into your main Visual Studio hive. This will replace the base installed version. Once it's installed, you'll see it marked as "Experimental" in Tools > Extensions and Updates to indicate you're running your experimental version. You can uninstall your version and go back to the originally installed version by choosing your version and clicking Uninstall. If you only install the VSIX, then the IDE will behave correctly (ie. new compiler and IDE behavior), but the Build operation or building from the command-line won't. To fix that, add a reference to the `Microsoft.Net.Compilers.Toolset` you built into your csproj. As shown below, you'll want to (1) add a nuget source pointing to your local build folder, (2) add the package reference, then (3) verify the Build Output of your project with a `#error version` included in your program. ![image](https://user-images.githubusercontent.com/12466233/81205885-25252a80-8f80-11ea-9d75-268c7fe6f3ed.png) ![image](https://user-images.githubusercontent.com/12466233/81205974-4128cc00-8f80-11ea-93ec-641d87662b12.png) ![image](https://user-images.githubusercontent.com/12466233/81206129-7fbe8680-8f80-11ea-9438-acc0481a3585.png) ### Deploying with command-line You can build and deploy with the following command: `.\Build.cmd -Configuration Release -deployExtensions -launch`. Then you can launch the `RoslynDev` hive with `devenv /rootSuffix RoslynDev`. ### Referencing bootstrap compiler If you made changes to a Roslyn compiler and want to build any projects with it, you can either use the Visual Studio hive where your **CompilerExtension** is installed, or from command line, run msbuild with `/p:BootstrapBuildPath=YourBootstrapBuildPath`. `YourBootstrapBuildPath` could be any directory on your machine so long as it had csc and vbc inside it. You can check the cibuild.cmd and see how it is used. ### Troubleshooting your setup To confirm what version of the compiler is being used, include `#error version` in your program and the compiler will produce a diagnostic including its own version as well as the language version it is operating under. You can also attach a debugger to Visual Studio and check the loaded modules, looking at the folder where the various `CodeAnalysis` modules were loaded from (the `RoslynDev` should load them somewhere under `AppData`, not from `Program File`). ### Testing on the [dotnet/runtime](https://github.com/dotnet/runtime) repo 1. make sure that you can build the `runtime` repo as baseline (run `build.cmd libs`, which should be sufficient to build all C# code, installing any prerequisites if prompted to) 2. `build.cmd -pack` on your `roslyn` repo 3. in `%userprofile%\.nuget\packages\microsoft.net.compilers.toolset` delete the version of the toolset that you just packed so that the new one will get put into the cache 4. modify your local enlistment of `runtime` as illustrated in [this commit](https://github.com/RikkiGibson/runtime/commit/da3c6d96c3764e571269b07650a374678b476384) then build again - add `<RestoreAdditionalProjectSources><PATH-TO-YOUR-ROSLYN-ENLISTMENT>\artifacts\packages\Debug\Shipping\</RestoreAdditionalProjectSources>` using the local path to your `roslyn` repo to `Directory.Build.props` - add `<MicrosoftNetCompilersToolsetVersion>3.9.0-dev</MicrosoftNetCompilersToolsetVersion>` with the package version you just packed (look in above artifacts folder) to `eng/Versions.props` ### Testing with extra IOperation validation Run `build.cmd -testIOperation` which sets the `ROSLYN_TEST_IOPERATION` environment variable to `true` and runs the tests. For running those tests in an IDE, the easiest is to find the `//#define ROSLYN_TEST_IOPERATION` directive and uncomment it. See more details in the [IOperation test hook](https://github.com/dotnet/roslyn/blob/main/docs/compilers/IOperation%20Test%20Hook.md) doc. ## Contributing Please see [Contributing Code](https://github.com/dotnet/roslyn/blob/main/CONTRIBUTING.md) for details on contributing changes back to the code.
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/Version.Details.xml
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21452.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>a9515db097e05728fcc2169d074eae3c6a4580d0</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="7.0.0-beta.21463.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>4b7c80f398fd3dcea03fdc4e454789b61181d300</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-5.21469.2"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>c1d8c6f043bc80425c6828455eb57f8a404759c6</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="7.0.0-beta.21463.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>4b7c80f398fd3dcea03fdc4e454789b61181d300</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
<?xml version="1.0" encoding="utf-8"?> <Dependencies> <ProductDependencies> <Dependency Name="XliffTasks" Version="1.0.0-beta.21215.1"> <Uri>https://github.com/dotnet/xliff-tasks</Uri> <Sha>7e80445ee82adbf9a8e6ae601ac5e239d982afaa</Sha> <SourceBuild RepoName="xliff-tasks" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build" Version="0.1.0-alpha.1.21452.1"> <Uri>https://github.com/dotnet/source-build</Uri> <Sha>a9515db097e05728fcc2169d074eae3c6a4580d0</Sha> <SourceBuild RepoName="source-build" ManagedOnly="true" /> </Dependency> </ProductDependencies> <ToolsetDependencies> <Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="7.0.0-beta.21472.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>8b2142306838fb8e155e12c1d8a9f59c9c4cd73f</Sha> <SourceBuild RepoName="arcade" ManagedOnly="true" /> </Dependency> <Dependency Name="Microsoft.Net.Compilers.Toolset" Version="4.0.0-5.21469.2"> <Uri>https://github.com/dotnet/roslyn</Uri> <Sha>c1d8c6f043bc80425c6828455eb57f8a404759c6</Sha> </Dependency> <Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="7.0.0-beta.21472.4"> <Uri>https://github.com/dotnet/arcade</Uri> <Sha>8b2142306838fb8e155e12c1d8a9f59c9c4cd73f</Sha> </Dependency> </ToolsetDependencies> </Dependencies>
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./eng/common/tools.ps1
# Initialize variables if they aren't already defined. # These may be defined as parameters of the importing script, or set after importing this script. # CI mode - set to true on CI server for PR validation build or official build. [bool]$ci = if (Test-Path variable:ci) { $ci } else { $false } # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. [string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' } # Set to true to opt out of outputting binary log while running in CI [bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false } # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. [bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog } # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. [bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci } # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). [bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false } # True to restore toolsets and dependencies. [bool]$restore = if (Test-Path variable:restore) { $restore } else { $true } # Adjusts msbuild verbosity level. [string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' } # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. [bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci } # Configures warning treatment in msbuild. [bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true } # Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json). [string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null } # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. [bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true } # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.ps1 [string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' } # True to use global NuGet cache instead of restoring packages to repository-local directory. [bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci } # True to exclude prerelease versions Visual Studio during build [bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false } # An array of names of processes to stop on script exit if prepareMachine is true. $processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') } $disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null } set-strictmode -version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first. [string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null } # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null } function Unzip([string]$zipfile, [string]$outpath) { Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) } # This will exec a process using the console and return it's exit code. # This will not throw when the process fails. # Returns process exit code. function Exec-Process([string]$command, [string]$commandArgs) { $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true return $global:LASTEXITCODE = $process.ExitCode } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Take the given block, print it, print what the block probably references from the current set of # variables using low-effort string matching, then run the block. # # This is intended to replace the pattern of manually copy-pasting a command, wrapping it in quotes, # and printing it using "Write-Host". The copy-paste method is more readable in build logs, but less # maintainable and less reliable. It is easy to make a mistake and modify the command without # properly updating the "Write-Host" line, resulting in misleading build logs. The probability of # this mistake makes the pattern hard to trust when it shows up in build logs. Finding the bug in # existing source code can also be difficult, because the strings are not aligned to each other and # the line may be 300+ columns long. # # By removing the need to maintain two copies of the command, Exec-BlockVerbosely avoids the issues. # # In Bash (or any posix-like shell), "set -x" prints usable verbose output automatically. # "Set-PSDebug" appears to be similar at first glance, but unfortunately, it isn't very useful: it # doesn't print any info about the variables being used by the command, which is normally the # interesting part to diagnose. function Exec-BlockVerbosely([scriptblock] $block) { Write-Host "--- Running script block:" $blockString = $block.ToString().Trim() Write-Host $blockString Write-Host "--- List of variables that might be used:" # For each variable x in the environment, check the block for a reference to x via simple "$x" or # "@x" syntax. This doesn't detect other ways to reference variables ("${x}" nor "$variable:x", # among others). It only catches what this function was originally written for: simple # command-line commands. $variableTable = Get-Variable | Where-Object { $blockString.Contains("`$$($_.Name)") -or $blockString.Contains("@$($_.Name)") } | Format-Table -AutoSize -HideTableHeaders -Wrap | Out-String Write-Host $variableTable.Trim() Write-Host "--- Executing:" & $block Write-Host "--- Done running script block!" } # createSdkLocationFile parameter enables a file being generated under the toolset directory # which writes the sdk's location into. This is only necessary for cmd --> powershell invocations # as dot sourcing isn't possible. function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) { if (Test-Path variable:global:_DotNetInstallDir) { return $global:_DotNetInstallDir } # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism $env:DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we do not need all ASP.NET packages restored. $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI. if ($ci) { $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 # In case of network error, try to log the current IP for reference Try-LogClientIpAddress } # Source Build uses DotNetCoreSdkDir variable if ($env:DotNetCoreSdkDir -ne $null) { $env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir } # Find the first path on %PATH% that contains the dotnet.exe if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) { $dotnetExecutable = GetExecutableFileName 'dotnet' $dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue if ($dotnetCmd -ne $null) { $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent } } $dotnetSdkVersion = $GlobalJson.tools.dotnet # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { $dotnetRoot = $env:DOTNET_INSTALL_DIR } else { $dotnetRoot = Join-Path $RepoRoot '.dotnet' if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) { if ($install) { InstallDotNetSdk $dotnetRoot $dotnetSdkVersion } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'" ExitWithExitCode 1 } } $env:DOTNET_INSTALL_DIR = $dotnetRoot } # Creates a temporary file under the toolset dir. # The following code block is protecting against concurrent access so that this function can # be called in parallel. if ($createSdkLocationFile) { do { $sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName()) } until (!(Test-Path $sdkCacheFileTemp)) Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot try { Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt') } catch { # Somebody beat us Remove-Item -Path $sdkCacheFileTemp } } # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. # It also ensures that VS msbuild will use the downloaded sdk targets. $env:PATH = "$dotnetRoot;$env:PATH" # Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build Write-PipelinePrependPath -Path $dotnetRoot Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0' Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1' return $global:_DotNetInstallDir = $dotnetRoot } function Retry($downloadBlock, $maxRetries = 5) { $retries = 1 while($true) { try { & $downloadBlock break } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ } if (++$retries -le $maxRetries) { $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)." Start-Sleep -Seconds $delayInSeconds } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts." break } } } function GetDotNetInstallScript([string] $dotnetRoot) { $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1' if (!(Test-Path $installScript)) { Create-Directory $dotnetRoot $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit $uri = "https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.ps1" Retry({ Write-Host "GET $uri" Invoke-WebRequest $uri -OutFile $installScript }) } return $installScript } function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) { InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath } function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = '', [string] $runtime = '', [bool] $skipNonVersionedFiles = $false, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $noPath) { $installScript = GetDotNetInstallScript $dotnetRoot $installParameters = @{ Version = $version InstallDir = $dotnetRoot } if ($architecture) { $installParameters.Architecture = $architecture } if ($runtime) { $installParameters.Runtime = $runtime } if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles } if ($noPath) { $installParameters.NoPath = $True } try { & $installScript @installParameters } catch { if ($runtimeSourceFeed -or $runtimeSourceFeedKey) { Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'" if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed } if ($runtimeSourceFeedKey) { $decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey) $decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes) $installParameters.FeedCredential = $decodedString } try { & $installScript @installParameters } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'." ExitWithExitCode 1 } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location." ExitWithExitCode 1 } } } # # Locates Visual Studio MSBuild installation. # The preference order for MSBuild to use is as follows: # # 1. MSBuild from an active VS command prompt # 2. MSBuild from a compatible VS installation # 3. MSBuild from the xcopy tool package # # Returns full path to msbuild.exe. # Throws on failure. # function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) { if (-not (IsWindowsPlatform)) { throw "Cannot initialize Visual Studio on non-Windows" } if (Test-Path variable:global:_MSBuildExe) { return $global:_MSBuildExe } # Minimum VS version to require. $vsMinVersionReqdStr = '16.8' $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr) # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: # https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview $defaultXCopyMSBuildVersion = '16.10.0-preview2' if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr } $vsMinVersion = [Version]::new($vsMinVersionStr) # Try msbuild command available in the environment. if ($env:VSINSTALLDIR -ne $null) { $msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue if ($msbuildCmd -ne $null) { # Workaround for https://github.com/dotnet/roslyn/issues/35793 # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+ $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0]) if ($msbuildVersion -ge $vsMinVersion) { return $global:_MSBuildExe = $msbuildCmd.Path } # Report error - the developer environment is initialized with incompatible VS version. throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window" } } # Locate Visual Studio installation or download x-copy msbuild. $vsInfo = LocateVisualStudio $vsRequirements if ($vsInfo -ne $null) { $vsInstallDir = $vsInfo.installationPath $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion } else { if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') { $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild' $vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0] } else { #if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download if($vsMinVersion -lt $vsMinVersionReqd){ Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible" $xcopyMSBuildVersion = $defaultXCopyMSBuildVersion } else{ # If the VS version IS compatible, look for an xcopy msbuild package # with a version matching VS. # Note: If this version does not exist, then an explicit version of xcopy msbuild # can be specified in global.json. This will be required for pre-release versions of msbuild. $vsMajorVersion = $vsMinVersion.Major $vsMinorVersion = $vsMinVersion.Minor $xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0" } } $vsInstallDir = $null if ($xcopyMSBuildVersion.Trim() -ine "none") { $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install if ($vsInstallDir -eq $null) { throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'." } } if ($vsInstallDir -eq $null) { throw 'Unable to find Visual Studio that has required version and components installed' } } $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" } $local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin" $local:Prefer64bit = if (Get-Member -InputObject $vsRequirements -Name 'Prefer64bit') { $vsRequirements.Prefer64bit } else { $false } if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) { $global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe" } else { $global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe" } return $global:_MSBuildExe } function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) { $env:VSINSTALLDIR = $vsInstallDir Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\") $vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\" if (Test-Path $vsSdkInstallDir) { Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir $env:VSSDKInstall = $vsSdkInstallDir } } function InstallXCopyMSBuild([string]$packageVersion) { return InitializeXCopyMSBuild $packageVersion -install $true } function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) { $packageName = 'RoslynTools.MSBuild' $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion" $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" if (!(Test-Path $packageDir)) { if (!$install) { return $null } Create-Directory $packageDir Write-Host "Downloading $packageName $packageVersion" $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath }) Unzip $packagePath $packageDir } return Join-Path $packageDir 'tools' } # # Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json. # # The following properties of tools.vs are recognized: # "version": "{major}.{minor}" # Two part minimal VS version, e.g. "15.9", "16.0", etc. # "components": ["componentId1", "componentId2", ...] # Array of ids of workload components that must be available in the VS instance. # See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017 # # Returns JSON describing the located VS instance (same format as returned by vswhere), # or $null if no instance meeting the requirements is found on the machine. # function LocateVisualStudio([object]$vsRequirements = $null){ if (-not (IsWindowsPlatform)) { throw "Cannot run vswhere on non-Windows platforms." } if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') { $vswhereVersion = $GlobalJson.tools.vswhere } else { $vswhereVersion = '2.5.2' } $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion" $vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe' if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir Write-Host 'Downloading vswhere' Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe }) } if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*') if (!$excludePrereleaseVS) { $args += '-prerelease' } if (Get-Member -InputObject $vsRequirements -Name 'version') { $args += '-version' $args += $vsRequirements.version } if (Get-Member -InputObject $vsRequirements -Name 'components') { foreach ($component in $vsRequirements.components) { $args += '-requires' $args += $component } } $vsInfo =& $vsWhereExe $args | ConvertFrom-Json if ($lastExitCode -ne 0) { return $null } # use first matching instance return $vsInfo[0] } function InitializeBuildTool() { if (Test-Path variable:global:_BuildTool) { # If the requested msbuild parameters do not match, clear the cached variables. if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) { Remove-Item variable:global:_BuildTool Remove-Item variable:global:_MSBuildExe } else { return $global:_BuildTool } } if (-not $msbuildEngine) { $msbuildEngine = GetDefaultMSBuildEngine } # Initialize dotnet cli if listed in 'tools' $dotnetRoot = $null if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { $dotnetRoot = InitializeDotNetCli -install:$restore } if ($msbuildEngine -eq 'dotnet') { if (!$dotnetRoot) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'." ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 } return $global:_BuildTool = $buildTool } function GetDefaultMSBuildEngine() { # Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows. if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { return 'vs' } if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { return 'dotnet' } Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." ExitWithExitCode 1 } function GetNuGetPackageCachePath() { if ($env:NUGET_PACKAGES -eq $null) { # Use local cache on CI to ensure deterministic build. # Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116 # use global cache in dev builds to avoid cost of downloading packages. # For directory normalization, see also: https://github.com/NuGet/Home/issues/7968 if ($useGlobalNuGetCache) { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' $env:RESTORENOCACHE = $true } } return $env:NUGET_PACKAGES } # Returns a full path to an Arcade SDK task project file. function GetSdkTaskProject([string]$taskName) { return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" } function InitializeNativeTools() { if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) { $nativeArgs= @{} if ($ci) { $nativeArgs = @{ InstallDirectory = "$ToolsDir" } } & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs } } function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj } $nugetCache = GetNuGetPackageCachePath $toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk' $toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt" if (Test-Path $toolsetLocationFile) { $path = Get-Content $toolsetLocationFile -TotalCount 1 if (Test-Path $path) { return $global:_ToolsetBuildProj = $path } } if (-not $restore) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 1 } $buildTool = InitializeBuildTool $proj = Join-Path $ToolsetDir 'restore.proj' $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' } '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile $path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1 if (!(Test-Path $path)) { throw "Invalid toolset path: $path" } return $global:_ToolsetBuildProj = $path } function ExitWithExitCode([int] $exitCode) { if ($ci -and $prepareMachine) { Stop-Processes } exit $exitCode } # Check if $LASTEXITCODE is a nonzero exit code (NZEC). If so, print a Azure Pipeline error for # diagnostics, then exit the script with the $LASTEXITCODE. function Exit-IfNZEC([string] $category = "General") { Write-Host "Exit code $LASTEXITCODE" if ($LASTEXITCODE -ne 0) { $message = "Last command failed with exit code $LASTEXITCODE." Write-PipelineTelemetryError -Force -Category $category -Message $message ExitWithExitCode $LASTEXITCODE } } function Stop-Processes() { Write-Host 'Killing running build processes...' foreach ($processName in $processesToStopOnExit) { Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process } } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild() { if ($pipelinesLog) { $buildTool = InitializeBuildTool if ($ci -and $buildTool.Tool -eq 'dotnet') { $env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20 $env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20 Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20' Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20' } if ($ci) { $env:NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY = 'true' $env:NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT = 6 $env:NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS = 1000 Write-PipelineSetVariable -Name 'NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY' -Value 'true' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT' -Value '6' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS' -Value '1000' } $toolsetBuildProject = InitializeToolset $basePath = Split-Path -parent $toolsetBuildProject $possiblePaths = @( # new scripts need to work with old packages, so we need to look for the old names/versions (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll')) (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.Arcade.Sdk.dll')) ) $selectedPath = $null foreach ($path in $possiblePaths) { if (Test-Path $path -PathType Leaf) { $selectedPath = $path break } } if (-not $selectedPath) { Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.' ExitWithExitCode 1 } $args += "/logger:$selectedPath" } MSBuild-Core @args } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild-Core() { if ($ci) { if (!$binaryLog -and !$excludeCIBinarylog) { Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.' ExitWithExitCode 1 } if ($nodeReuse) { Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.' ExitWithExitCode 1 } } $buildTool = InitializeBuildTool $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci" if ($warnAsError) { $cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true' } else { $cmdArgs += ' /p:TreatWarningsAsErrors=false' } foreach ($arg in $args) { if ($null -ne $arg -and $arg.Trim() -ne "") { if ($arg.EndsWith('\')) { $arg = $arg + "\" } $cmdArgs += " `"$arg`"" } } $env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs" $exitCode = Exec-Process $buildTool.Path $cmdArgs if ($exitCode -ne 0) { # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red $buildLog = GetMSBuildBinaryLogCommandLineArgument $args if ($null -ne $buildLog) { Write-Host "See log: $buildLog" -ForegroundColor DarkGray } if ($ci) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 } else { ExitWithExitCode $exitCode } } } function GetMSBuildBinaryLogCommandLineArgument($arguments) { foreach ($argument in $arguments) { if ($argument -ne $null) { $arg = $argument.Trim() if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) { return $arg.Substring('/bl:'.Length) } if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) { return $arg.Substring('/binaryLogger:'.Length) } } } return $null } function GetExecutableFileName($baseName) { if (IsWindowsPlatform) { return "$baseName.exe" } else { return $baseName } } function IsWindowsPlatform() { return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT } function Get-Darc($version) { $darcPath = "$TempDir\darc\$(New-Guid)" if ($version -ne $null) { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host } else { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host } return "$darcPath\darc.exe" } . $PSScriptRoot\pipeline-logging-functions.ps1 $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\') $EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..') $ArtifactsDir = Join-Path $RepoRoot 'artifacts' $ToolsetDir = Join-Path $ArtifactsDir 'toolset' $ToolsDir = Join-Path $RepoRoot '.tools' $LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration $TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration $GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json # true if global.json contains a "runtimes" section $globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false } Create-Directory $ToolsetDir Create-Directory $TempDir Create-Directory $LogDir Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir Write-PipelineSetVariable -Name 'TMP' -Value $TempDir # Import custom tools configuration, if present in the repo. # Note: Import in global scope so that the script set top-level variables without qualification. if (!$disableConfigureToolsetImport) { $configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1' if (Test-Path $configureToolsetScript) { . $configureToolsetScript if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) { if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) { Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code' ExitWithExitCode $LastExitCode } } } } function Try-LogClientIpAddress() { Write-Host "Attempting to log this client's IP for Azure Package feed telemetry purposes" try { $result = Invoke-WebRequest -Uri "http://co1.msedge.net/fdv2/diagnostics.aspx" -UseBasicParsing $lines = $result.Content.Split([Environment]::NewLine) $socketIp = $lines | Select-String -Pattern "^Socket IP:.*" Write-Host $socketIp $clientIp = $lines | Select-String -Pattern "^Client IP:.*" Write-Host $clientIp } catch { Write-Host "Unable to get this machine's effective IP address for logging: $_" } }
# Initialize variables if they aren't already defined. # These may be defined as parameters of the importing script, or set after importing this script. # CI mode - set to true on CI server for PR validation build or official build. [bool]$ci = if (Test-Path variable:ci) { $ci } else { $false } # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. [string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' } # Set to true to opt out of outputting binary log while running in CI [bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false } # Set to true to output binary log from msbuild. Note that emitting binary log slows down the build. [bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog } # Set to true to use the pipelines logger which will enable Azure logging output. # https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md # This flag is meant as a temporary opt-opt for the feature while validate it across # our consumers. It will be deleted in the future. [bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci } # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). [bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false } # True to restore toolsets and dependencies. [bool]$restore = if (Test-Path variable:restore) { $restore } else { $true } # Adjusts msbuild verbosity level. [string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' } # Set to true to reuse msbuild nodes. Recommended to not reuse on CI. [bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci } # Configures warning treatment in msbuild. [bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true } # Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json). [string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null } # True to attempt using .NET Core already that meets requirements specified in global.json # installed on the machine instead of downloading one. [bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true } # Enable repos to use a particular version of the on-line dotnet-install scripts. # default URL: https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.ps1 [string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' } # True to use global NuGet cache instead of restoring packages to repository-local directory. [bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci } # True to exclude prerelease versions Visual Studio during build [bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false } # An array of names of processes to stop on script exit if prepareMachine is true. $processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') } $disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null } set-strictmode -version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first. [string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null } # Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed [string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null } function Create-Directory ([string[]] $path) { New-Item -Path $path -Force -ItemType 'Directory' | Out-Null } function Unzip([string]$zipfile, [string]$outpath) { Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) } # This will exec a process using the console and return it's exit code. # This will not throw when the process fails. # Returns process exit code. function Exec-Process([string]$command, [string]$commandArgs) { $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = $command $startInfo.Arguments = $commandArgs $startInfo.UseShellExecute = $false $startInfo.WorkingDirectory = Get-Location $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $finished = $false try { while (-not $process.WaitForExit(100)) { # Non-blocking loop done to allow ctr-c interrupts } $finished = $true return $global:LASTEXITCODE = $process.ExitCode } finally { # If we didn't finish then an error occurred or the user hit ctrl-c. Either # way kill the process if (-not $finished) { $process.Kill() } } } # Take the given block, print it, print what the block probably references from the current set of # variables using low-effort string matching, then run the block. # # This is intended to replace the pattern of manually copy-pasting a command, wrapping it in quotes, # and printing it using "Write-Host". The copy-paste method is more readable in build logs, but less # maintainable and less reliable. It is easy to make a mistake and modify the command without # properly updating the "Write-Host" line, resulting in misleading build logs. The probability of # this mistake makes the pattern hard to trust when it shows up in build logs. Finding the bug in # existing source code can also be difficult, because the strings are not aligned to each other and # the line may be 300+ columns long. # # By removing the need to maintain two copies of the command, Exec-BlockVerbosely avoids the issues. # # In Bash (or any posix-like shell), "set -x" prints usable verbose output automatically. # "Set-PSDebug" appears to be similar at first glance, but unfortunately, it isn't very useful: it # doesn't print any info about the variables being used by the command, which is normally the # interesting part to diagnose. function Exec-BlockVerbosely([scriptblock] $block) { Write-Host "--- Running script block:" $blockString = $block.ToString().Trim() Write-Host $blockString Write-Host "--- List of variables that might be used:" # For each variable x in the environment, check the block for a reference to x via simple "$x" or # "@x" syntax. This doesn't detect other ways to reference variables ("${x}" nor "$variable:x", # among others). It only catches what this function was originally written for: simple # command-line commands. $variableTable = Get-Variable | Where-Object { $blockString.Contains("`$$($_.Name)") -or $blockString.Contains("@$($_.Name)") } | Format-Table -AutoSize -HideTableHeaders -Wrap | Out-String Write-Host $variableTable.Trim() Write-Host "--- Executing:" & $block Write-Host "--- Done running script block!" } # createSdkLocationFile parameter enables a file being generated under the toolset directory # which writes the sdk's location into. This is only necessary for cmd --> powershell invocations # as dot sourcing isn't possible. function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) { if (Test-Path variable:global:_DotNetInstallDir) { return $global:_DotNetInstallDir } # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism $env:DOTNET_MULTILEVEL_LOOKUP=0 # Disable first run since we do not need all ASP.NET packages restored. $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 # Disable telemetry on CI. if ($ci) { $env:DOTNET_CLI_TELEMETRY_OPTOUT=1 # In case of network error, try to log the current IP for reference Try-LogClientIpAddress } # Source Build uses DotNetCoreSdkDir variable if ($env:DotNetCoreSdkDir -ne $null) { $env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir } # Find the first path on %PATH% that contains the dotnet.exe if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) { $dotnetExecutable = GetExecutableFileName 'dotnet' $dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue if ($dotnetCmd -ne $null) { $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent } } $dotnetSdkVersion = $GlobalJson.tools.dotnet # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { $dotnetRoot = $env:DOTNET_INSTALL_DIR } else { $dotnetRoot = Join-Path $RepoRoot '.dotnet' if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) { if ($install) { InstallDotNetSdk $dotnetRoot $dotnetSdkVersion } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'" ExitWithExitCode 1 } } $env:DOTNET_INSTALL_DIR = $dotnetRoot } # Creates a temporary file under the toolset dir. # The following code block is protecting against concurrent access so that this function can # be called in parallel. if ($createSdkLocationFile) { do { $sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName()) } until (!(Test-Path $sdkCacheFileTemp)) Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot try { Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt') } catch { # Somebody beat us Remove-Item -Path $sdkCacheFileTemp } } # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom # build steps from using anything other than what we've downloaded. # It also ensures that VS msbuild will use the downloaded sdk targets. $env:PATH = "$dotnetRoot;$env:PATH" # Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build Write-PipelinePrependPath -Path $dotnetRoot Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0' Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1' return $global:_DotNetInstallDir = $dotnetRoot } function Retry($downloadBlock, $maxRetries = 5) { $retries = 1 while($true) { try { & $downloadBlock break } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ } if (++$retries -le $maxRetries) { $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)." Start-Sleep -Seconds $delayInSeconds } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts." break } } } function GetDotNetInstallScript([string] $dotnetRoot) { $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1' if (!(Test-Path $installScript)) { Create-Directory $dotnetRoot $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit $uri = "https://dotnet.microsoft.com/download/dotnet/scripts/$dotnetInstallScriptVersion/dotnet-install.ps1" Retry({ Write-Host "GET $uri" Invoke-WebRequest $uri -OutFile $installScript }) } return $installScript } function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) { InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath } function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = '', [string] $runtime = '', [bool] $skipNonVersionedFiles = $false, [string] $runtimeSourceFeed = '', [string] $runtimeSourceFeedKey = '', [switch] $noPath) { $installScript = GetDotNetInstallScript $dotnetRoot $installParameters = @{ Version = $version InstallDir = $dotnetRoot } if ($architecture) { $installParameters.Architecture = $architecture } if ($runtime) { $installParameters.Runtime = $runtime } if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles } if ($noPath) { $installParameters.NoPath = $True } try { & $installScript @installParameters } catch { if ($runtimeSourceFeed -or $runtimeSourceFeedKey) { Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'" if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed } if ($runtimeSourceFeedKey) { $decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey) $decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes) $installParameters.FeedCredential = $decodedString } try { & $installScript @installParameters } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'." ExitWithExitCode 1 } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location." ExitWithExitCode 1 } } } # # Locates Visual Studio MSBuild installation. # The preference order for MSBuild to use is as follows: # # 1. MSBuild from an active VS command prompt # 2. MSBuild from a compatible VS installation # 3. MSBuild from the xcopy tool package # # Returns full path to msbuild.exe. # Throws on failure. # function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) { if (-not (IsWindowsPlatform)) { throw "Cannot initialize Visual Studio on non-Windows" } if (Test-Path variable:global:_MSBuildExe) { return $global:_MSBuildExe } # Minimum VS version to require. $vsMinVersionReqdStr = '16.8' $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr) # If the version of msbuild is going to be xcopied, # use this version. Version matches a package here: # https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview $defaultXCopyMSBuildVersion = '16.10.0-preview2' if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr } $vsMinVersion = [Version]::new($vsMinVersionStr) # Try msbuild command available in the environment. if ($env:VSINSTALLDIR -ne $null) { $msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue if ($msbuildCmd -ne $null) { # Workaround for https://github.com/dotnet/roslyn/issues/35793 # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+ $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0]) if ($msbuildVersion -ge $vsMinVersion) { return $global:_MSBuildExe = $msbuildCmd.Path } # Report error - the developer environment is initialized with incompatible VS version. throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window" } } # Locate Visual Studio installation or download x-copy msbuild. $vsInfo = LocateVisualStudio $vsRequirements if ($vsInfo -ne $null) { $vsInstallDir = $vsInfo.installationPath $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion } else { if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') { $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild' $vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0] } else { #if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download if($vsMinVersion -lt $vsMinVersionReqd){ Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible" $xcopyMSBuildVersion = $defaultXCopyMSBuildVersion } else{ # If the VS version IS compatible, look for an xcopy msbuild package # with a version matching VS. # Note: If this version does not exist, then an explicit version of xcopy msbuild # can be specified in global.json. This will be required for pre-release versions of msbuild. $vsMajorVersion = $vsMinVersion.Major $vsMinorVersion = $vsMinVersion.Minor $xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0" } } $vsInstallDir = $null if ($xcopyMSBuildVersion.Trim() -ine "none") { $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install if ($vsInstallDir -eq $null) { throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'." } } if ($vsInstallDir -eq $null) { throw 'Unable to find Visual Studio that has required version and components installed' } } $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" } $local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin" $local:Prefer64bit = if (Get-Member -InputObject $vsRequirements -Name 'Prefer64bit') { $vsRequirements.Prefer64bit } else { $false } if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) { $global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe" } else { $global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe" } return $global:_MSBuildExe } function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) { $env:VSINSTALLDIR = $vsInstallDir Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\") $vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\" if (Test-Path $vsSdkInstallDir) { Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir $env:VSSDKInstall = $vsSdkInstallDir } } function InstallXCopyMSBuild([string]$packageVersion) { return InitializeXCopyMSBuild $packageVersion -install $true } function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) { $packageName = 'RoslynTools.MSBuild' $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion" $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" if (!(Test-Path $packageDir)) { if (!$install) { return $null } Create-Directory $packageDir Write-Host "Downloading $packageName $packageVersion" $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit Retry({ Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath }) Unzip $packagePath $packageDir } return Join-Path $packageDir 'tools' } # # Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json. # # The following properties of tools.vs are recognized: # "version": "{major}.{minor}" # Two part minimal VS version, e.g. "15.9", "16.0", etc. # "components": ["componentId1", "componentId2", ...] # Array of ids of workload components that must be available in the VS instance. # See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017 # # Returns JSON describing the located VS instance (same format as returned by vswhere), # or $null if no instance meeting the requirements is found on the machine. # function LocateVisualStudio([object]$vsRequirements = $null){ if (-not (IsWindowsPlatform)) { throw "Cannot run vswhere on non-Windows platforms." } if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') { $vswhereVersion = $GlobalJson.tools.vswhere } else { $vswhereVersion = '2.5.2' } $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion" $vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe' if (!(Test-Path $vsWhereExe)) { Create-Directory $vsWhereDir Write-Host 'Downloading vswhere' Retry({ Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe }) } if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs } $args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*') if (!$excludePrereleaseVS) { $args += '-prerelease' } if (Get-Member -InputObject $vsRequirements -Name 'version') { $args += '-version' $args += $vsRequirements.version } if (Get-Member -InputObject $vsRequirements -Name 'components') { foreach ($component in $vsRequirements.components) { $args += '-requires' $args += $component } } $vsInfo =& $vsWhereExe $args | ConvertFrom-Json if ($lastExitCode -ne 0) { return $null } # use first matching instance return $vsInfo[0] } function InitializeBuildTool() { if (Test-Path variable:global:_BuildTool) { # If the requested msbuild parameters do not match, clear the cached variables. if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) { Remove-Item variable:global:_BuildTool Remove-Item variable:global:_MSBuildExe } else { return $global:_BuildTool } } if (-not $msbuildEngine) { $msbuildEngine = GetDefaultMSBuildEngine } # Initialize dotnet cli if listed in 'tools' $dotnetRoot = $null if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { $dotnetRoot = InitializeDotNetCli -install:$restore } if ($msbuildEngine -eq 'dotnet') { if (!$dotnetRoot) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'." ExitWithExitCode 1 } $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet') $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore } catch { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_ ExitWithExitCode 1 } $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS } } else { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 } return $global:_BuildTool = $buildTool } function GetDefaultMSBuildEngine() { # Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows. if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') { return 'vs' } if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') { return 'dotnet' } Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." ExitWithExitCode 1 } function GetNuGetPackageCachePath() { if ($env:NUGET_PACKAGES -eq $null) { # Use local cache on CI to ensure deterministic build. # Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116 # use global cache in dev builds to avoid cost of downloading packages. # For directory normalization, see also: https://github.com/NuGet/Home/issues/7968 if ($useGlobalNuGetCache) { $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\' } else { $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\' $env:RESTORENOCACHE = $true } } return $env:NUGET_PACKAGES } # Returns a full path to an Arcade SDK task project file. function GetSdkTaskProject([string]$taskName) { return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" } function InitializeNativeTools() { if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) { $nativeArgs= @{} if ($ci) { $nativeArgs = @{ InstallDirectory = "$ToolsDir" } } & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs } } function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj } $nugetCache = GetNuGetPackageCachePath $toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk' $toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt" if (Test-Path $toolsetLocationFile) { $path = Get-Content $toolsetLocationFile -TotalCount 1 if (Test-Path $path) { return $global:_ToolsetBuildProj = $path } } if (-not $restore) { Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 1 } $buildTool = InitializeBuildTool $proj = Join-Path $ToolsetDir 'restore.proj' $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' } '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile $path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1 if (!(Test-Path $path)) { throw "Invalid toolset path: $path" } return $global:_ToolsetBuildProj = $path } function ExitWithExitCode([int] $exitCode) { if ($ci -and $prepareMachine) { Stop-Processes } exit $exitCode } # Check if $LASTEXITCODE is a nonzero exit code (NZEC). If so, print a Azure Pipeline error for # diagnostics, then exit the script with the $LASTEXITCODE. function Exit-IfNZEC([string] $category = "General") { Write-Host "Exit code $LASTEXITCODE" if ($LASTEXITCODE -ne 0) { $message = "Last command failed with exit code $LASTEXITCODE." Write-PipelineTelemetryError -Force -Category $category -Message $message ExitWithExitCode $LASTEXITCODE } } function Stop-Processes() { Write-Host 'Killing running build processes...' foreach ($processName in $processesToStopOnExit) { Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process } } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild() { if ($pipelinesLog) { $buildTool = InitializeBuildTool if ($ci -and $buildTool.Tool -eq 'dotnet') { $env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20 $env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20 Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20' Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20' } Enable-Nuget-EnhancedRetry $toolsetBuildProject = InitializeToolset $basePath = Split-Path -parent $toolsetBuildProject $possiblePaths = @( # new scripts need to work with old packages, so we need to look for the old names/versions (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll')) (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.ArcadeLogging.dll')), (Join-Path $basePath (Join-Path netcoreapp3.1 'Microsoft.DotNet.Arcade.Sdk.dll')) ) $selectedPath = $null foreach ($path in $possiblePaths) { if (Test-Path $path -PathType Leaf) { $selectedPath = $path break } } if (-not $selectedPath) { Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.' ExitWithExitCode 1 } $args += "/logger:$selectedPath" } MSBuild-Core @args } # # Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. # The arguments are automatically quoted. # Terminates the script if the build fails. # function MSBuild-Core() { if ($ci) { if (!$binaryLog -and !$excludeCIBinarylog) { Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.' ExitWithExitCode 1 } if ($nodeReuse) { Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.' ExitWithExitCode 1 } } Enable-Nuget-EnhancedRetry $buildTool = InitializeBuildTool $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci" if ($warnAsError) { $cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true' } else { $cmdArgs += ' /p:TreatWarningsAsErrors=false' } foreach ($arg in $args) { if ($null -ne $arg -and $arg.Trim() -ne "") { if ($arg.EndsWith('\')) { $arg = $arg + "\" } $cmdArgs += " `"$arg`"" } } $env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs" $exitCode = Exec-Process $buildTool.Path $cmdArgs if ($exitCode -ne 0) { # We should not Write-PipelineTaskError here because that message shows up in the build summary # The build already logged an error, that's the reason it failed. Producing an error here only adds noise. Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red $buildLog = GetMSBuildBinaryLogCommandLineArgument $args if ($null -ne $buildLog) { Write-Host "See log: $buildLog" -ForegroundColor DarkGray } if ($ci) { Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error ExitWithExitCode 0 } else { ExitWithExitCode $exitCode } } } function GetMSBuildBinaryLogCommandLineArgument($arguments) { foreach ($argument in $arguments) { if ($argument -ne $null) { $arg = $argument.Trim() if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) { return $arg.Substring('/bl:'.Length) } if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) { return $arg.Substring('/binaryLogger:'.Length) } } } return $null } function GetExecutableFileName($baseName) { if (IsWindowsPlatform) { return "$baseName.exe" } else { return $baseName } } function IsWindowsPlatform() { return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT } function Get-Darc($version) { $darcPath = "$TempDir\darc\$(New-Guid)" if ($version -ne $null) { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host } else { & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host } return "$darcPath\darc.exe" } . $PSScriptRoot\pipeline-logging-functions.ps1 $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\') $EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..') $ArtifactsDir = Join-Path $RepoRoot 'artifacts' $ToolsetDir = Join-Path $ArtifactsDir 'toolset' $ToolsDir = Join-Path $RepoRoot '.tools' $LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration $TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration $GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json # true if global.json contains a "runtimes" section $globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false } Create-Directory $ToolsetDir Create-Directory $TempDir Create-Directory $LogDir Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir Write-PipelineSetVariable -Name 'TMP' -Value $TempDir # Import custom tools configuration, if present in the repo. # Note: Import in global scope so that the script set top-level variables without qualification. if (!$disableConfigureToolsetImport) { $configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1' if (Test-Path $configureToolsetScript) { . $configureToolsetScript if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) { if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) { Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code' ExitWithExitCode $LastExitCode } } } } function Try-LogClientIpAddress() { Write-Host "Attempting to log this client's IP for Azure Package feed telemetry purposes" try { $result = Invoke-WebRequest -Uri "http://co1.msedge.net/fdv2/diagnostics.aspx" -UseBasicParsing $lines = $result.Content.Split([Environment]::NewLine) $socketIp = $lines | Select-String -Pattern "^Socket IP:.*" Write-Host $socketIp $clientIp = $lines | Select-String -Pattern "^Client IP:.*" Write-Host $clientIp } catch { Write-Host "Unable to get this machine's effective IP address for logging: $_" } } # # If $ci flag is set, turn on (and log that we did) special environment variables for improved Nuget client retry logic. # function Enable-Nuget-EnhancedRetry() { if ($ci) { Write-Host "Setting NUGET enhanced retry environment variables" $env:NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY = 'true' $env:NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT = 6 $env:NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS = 1000 Write-PipelineSetVariable -Name 'NUGET_ENABLE_EXPERIMENTAL_HTTP_RETRY' -Value 'true' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_MAX_NETWORK_TRY_COUNT' -Value '6' Write-PipelineSetVariable -Name 'NUGET_EXPERIMENTAL_NETWORK_RETRY_DELAY_MILLISECONDS' -Value '1000' } }
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./global.json
{ "sdk": { "version": "6.0.100-preview.7.21379.14", "allowPrerelease": true, "rollForward": "major" }, "tools": { "dotnet": "6.0.100-preview.7.21379.14", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.21463.4", "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.21463.4" } }
{ "sdk": { "version": "6.0.100-rc.1.21463.6", "allowPrerelease": true, "rollForward": "major" }, "tools": { "dotnet": "6.0.100-rc.1.21463.6", "vs": { "version": "16.10" }, "xcopy-msbuild": "16.10.0-preview2" }, "msbuild-sdks": { "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.21472.4", "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.21472.4" } }
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests : WellKnownAttributesTestBase { static readonly string[] s_autoPropAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }; static readonly string[] s_backingFieldAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; #region Function Tests [Fact, WorkItem(26464, "https://github.com/dotnet/roslyn/issues/26464")] public void TestNullInAssemblyVersionAttribute() { var source = @" [assembly: System.Reflection.AssemblyVersionAttribute(null)] class Program { }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (2,55): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersionAttribute(null)] Diagnostic(ErrorCode.ERR_InvalidVersionFormat, "null").WithLocation(2, 55) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void TestQuickAttributeChecker() { var predefined = QuickAttributeChecker.Predefined; var typeForwardedTo = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeForwardedTo")); var typeIdentifier = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeIdentifier")); Assert.True(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeForwardedTo)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.None)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeForwardedTo)); Assert.True(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.None)); var alias1 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias1")); var checker1 = WithAliases(predefined, "using alias1 = TypeForwardedToAttribute;"); Assert.True(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1a = WithAliases(checker1, "using alias1 = TypeIdentifierAttribute;"); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1b = WithAliases(checker1, "using alias2 = TypeIdentifierAttribute;"); var alias2 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias2")); Assert.True(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); Assert.False(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeForwardedTo)); Assert.True(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeIdentifier)); var checker3 = WithAliases(predefined, "using alias3 = TypeForwardedToAttribute; using alias3 = TypeIdentifierAttribute;"); var alias3 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias3")); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeForwardedTo)); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeIdentifier)); QuickAttributeChecker WithAliases(QuickAttributeChecker checker, string aliases) { var nodes = Parse(aliases).GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>(); var list = new SyntaxList<UsingDirectiveSyntax>().AddRange(nodes); return checker.AddAliasesIfAny(list); } } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant // but C won't exist "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithDiagnostic() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' // but C won't exist "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithStaticUsing() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using static RefersToLibAttribute; // Binding this will cause a lookup for 'C' in 'lib'. // Such lookup requires binding 'TypeForwardedTo' attributes (and aliases), but we should not bind other usings, to avoid an infinite recursion. [assembly: System.Reflection.AssemblyTitleAttribute(""title"")] public class Ignore { public void UseStaticUsing() { Method(); } } "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } public static void Method() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); var newLibComp3 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp3.SourceAssembly.GetAttributes(); newLibComp3.VerifyDiagnostics(); } /// <summary> /// Looking up C explicitly after calling GetAttributes will cause <see cref="SourceAssemblySymbol.GetForwardedTypes"/> to use the cached attributes, rather that do partial binding /// </summary> [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithCheckAttributes() { var cDefinition_cs = @"public class C { }"; var derivedDefinition_cs = @"public class Derived : C { }"; var typeForward_cs = @" [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] "; var origLibComp = CreateCompilation(cDefinition_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithDerivedAndReferenceToLib = CreateCompilation(typeForward_cs + derivedDefinition_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithDerivedAndReferenceToLib.VerifyDiagnostics(); var compWithC = CreateCompilation(cDefinition_cs, assemblyName: "new"); compWithC.VerifyDiagnostics(); var newLibComp = CreateCompilation(typeForward_cs, references: new[] { compWithDerivedAndReferenceToLib.EmitToImageReference(), compWithC.EmitToImageReference() }, assemblyName: "lib"); var attribute = newLibComp.SourceAssembly.GetAttributes().Single(); // GetAttributes binds all attributes Assert.Equal("System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(C))", attribute.ToString()); var derived = (NamedTypeSymbol)newLibComp.GetMember("Derived"); var c = derived.BaseType(); // get C Assert.Equal("C", c.ToTestDisplayString()); Assert.False(c.IsErrorType()); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType_WithAlias() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using alias1 = System.Runtime.CompilerServices.TypeForwardedToAttribute; [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: alias1(typeof(C))] // but C is forwarded via alias "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant public class C { } // and C exists here "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' public class C : System.Attribute { } // and C exists here "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] public void TestAssemblyAttributes() { var source = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Roslyn.Compilers.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.Test.Utilities"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.VisualBasic"")] class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { Symbol assembly = m.ContainingSymbol; var attrs = assembly.GetAttributes(); Assert.Equal(5, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.UnitTests"")", attrs[0].ToString()); attrs[1].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp"")", attrs[1].ToString()); attrs[2].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.UnitTests"")", attrs[2].ToString()); attrs[3].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.Test.Utilities"")", attrs[3].ToString()); attrs[4].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.VisualBasic"")", attrs[4].ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnStringParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { } } [Mark(b: new string[] { ""Hello"", ""World"" }, a: true)] [Mark(b: ""Hello"", true)] static class Program { }", parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (11,2): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Mark(b: new string[] { "Hello", "World" }, a: true)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"Mark(b: new string[] { ""Hello"", ""World"" }, a: true)").WithLocation(11, 2), // (12,7): error CS8323: Named argument 'b' is used out-of-position but is followed by an unnamed argument // [Mark(b: "Hello", true)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(12, 7) ); } [Fact] public void TestNullAsParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(params object[] b) { } } [Mark(null)] static class Program { }"); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnOrderedObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, b: new object[] { ""Hello"", ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: new object[] { ""Hello"", ""World"" }, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument2() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { A = a; B = b; } public bool A { get; } public object[] B { get; } } [Mark(b: ""Hello"", a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B.Length={attr.B.Length}, B[0]={attr.B[0]}""); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A=True, B.Length=1, B[0]=Hello"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument3() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument4() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument5() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: null, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write(attr.B == null); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnNonParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(int a, int b) { A = a; B = b; } public int A { get; } public int B { get; } } [Mark(b: 42, a: 1)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B={attr.B}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A=1, B=42"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, 0 }, attributeData.ConstructorArgumentsSourceIndices); } [WorkItem(984896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984896")] [Fact] public void TestAssemblyAttributesErr() { string code = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using M = System.Math; namespace My { using A.B; // TODO: <Insert justification for suppressing TestId> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Test"",""TestId"",Justification=""<Pending>"")] public unsafe partial class A : C, I { } } "; var source = CreateCompilationWithMscorlib40AndSystemCore(code); // the following should not crash source.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, source.SyntaxTrees[0], filterSpanWithinTree: null, includeEarlierStages: true); } [Fact, WorkItem(545326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545326")] public void TestAssemblyAttributes_Bug13670() { var source = @" using System; [assembly: A(Derived.Str)] public class A: Attribute { public A(string x){} public static void Main() {} } public class Derived: Base { internal const string Str = ""temp""; public override int Goo { get { return 1; } } } public class Base { public virtual int Goo { get { return 0; } } } "; CompileAndVerify(source); } [Fact] public void TestAssemblyAttributesReflection() { var compilation = CreateCompilation(@" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // These are not pseudo attributes, but encoded as bits in metadata [assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] [assembly: AssemblyCultureAttribute("""")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] [assembly: AssemblyVersion(""1.2.*"")] [assembly: AssemblyFileVersionAttribute(""4.3.2.100"")] class C { public static void Main() {} } "); var attrs = compilation.Assembly.GetAttributes(); Assert.Equal(8, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyAlgorithmIdAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5); Assert.Equal(@"System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)", a.ToString()); break; case "AssemblyCultureAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, ""); Assert.Equal(@"System.Reflection.AssemblyCultureAttribute("""")", a.ToString()); break; case "AssemblyDelaySignAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal(@"System.Reflection.AssemblyDelaySignAttribute(true)", a.ToString()); break; case "AssemblyFlagsAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)AssemblyNameFlags.Retargetable); Assert.Equal(@"System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.Retargetable)", a.ToString()); break; case "AssemblyKeyFileAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "MyKey.snk"); Assert.Equal(@"System.Reflection.AssemblyKeyFileAttribute(""MyKey.snk"")", a.ToString()); break; case "AssemblyKeyNameAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "Key Name"); Assert.Equal(@"System.Reflection.AssemblyKeyNameAttribute(""Key Name"")", a.ToString()); break; case "AssemblyVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "1.2.*"); Assert.Equal(@"System.Reflection.AssemblyVersionAttribute(""1.2.*"")", a.ToString()); break; case "AssemblyFileVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "4.3.2.100"); Assert.Equal(@"System.Reflection.AssemblyFileVersionAttribute(""4.3.2.100"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } // Verify that resolving an attribute defined within a class on a class does not cause infinite recursion [Fact] public void TestAttributesOnClassDefinedInClass() { var compilation = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [A.X()] public class A { [AttributeUsage(AttributeTargets.All, allowMultiple = true)] public class XAttribute : Attribute { } } class C { public static void Main() {} } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("A.XAttribute", attrs.First().AttributeClass.ToDisplayString()); } [Fact] public void TestAttributesOnClassWithConstantDefinedInClass() { var compilation = CreateCompilation(@" using System; [Attr(Goo.p)] class Goo { private const object p = null; } internal class AttrAttribute : Attribute { public AttrAttribute(object p) { } } class C { public static void Main() { } } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("Goo").GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue<object>(0, TypedConstantKind.Primitive, null); } [Fact] public void TestAttributeEmit() { var compilation = CreateCompilation(@" using System; public enum e1 { a, b, c } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute(int i) { } public XAttribute(int i, string s) { } public XAttribute(int i, string s, e1 e) { } public XAttribute(object[] o) { } public XAttribute(int[] i) { } public XAttribute(int[] i, string[] s) { } public XAttribute(int[] i, string[] s, e1[] e) { } public int pi { get; set; } public string ps { get; set; } public e1 pe { get; set; } } [X(1, ""hello"", e1.a)] [X(new int[] { 1 }, new string[] { ""hello"" }, new e1[] { e1.a, e1.b, e1.c })] [X(new object[] { 1, ""hello"", e1.a })] class C { public static void Main() {} } "); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("XAttribute..ctor(int)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Attribute..ctor()"" IL_0006: ret }"); } [Fact] public void TestAttributesOnClassProperty() { var compilation = CreateCompilation(@" using System; public class A { [CLSCompliant(true)] public string Prop { get { return null; } } } class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var prop = type.GetMember("Prop"); var attrs = prop.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal("System.CLSCompliantAttribute", attrs.First().AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688268")] [Fact] public void Bug688268() { var compilation = CreateCompilation(@" using System; using System.Runtime.InteropServices; using System.Security; public interface I { void _VtblGap1_30(); void _VtblGaP1_30(); } "); System.Action<ModuleSymbol> metadataValidator = delegate (ModuleSymbol module) { var metadata = ((PEModuleSymbol)module).Module; var typeI = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("I").Single(); var methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle); Assert.Equal(2, methods.Count); var e = methods.GetEnumerator(); e.MoveNext(); var flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, flags); e.MoveNext(); flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract, flags); }; CompileAndVerify( compilation, sourceSymbolValidator: null, symbolValidator: metadataValidator); } [Fact] public void TestAttributesOnPropertyAndGetSet() { string source = @" using System; [AObject(typeof(object), O = A.obj)] public class A { internal const object obj = null; public string RProp { [AObject(new object[] { typeof(string) })] get { return null; } } [AObject(new object[] { 1, ""two"", typeof(string), 3.1415926 })] public object WProp { [AObject(new object[] { new object[] { typeof(string) } })] set { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal("AObjectAttribute(typeof(object), O = null)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeof(object)); attrs.First().VerifyNamedArgumentValue<object>(0, "O", TypedConstantKind.Primitive, null); var prop = type.GetMember<PropertySymbol>("RProp"); attrs = prop.GetMethod.GetAttributes(); Assert.Equal("AObjectAttribute({typeof(string)})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { typeof(string) }); prop = type.GetMember<PropertySymbol>("WProp"); attrs = prop.GetAttributes(); Assert.Equal(@"AObjectAttribute({1, ""two"", typeof(string), 3.1415926})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { 1, "two", typeof(string), 3.1415926 }); attrs = prop.SetMethod.GetAttributes(); Assert.Equal(@"AObjectAttribute({{typeof(string)}})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { new object[] { typeof(string) } }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestFieldAttributeOnPropertyInCSharp7_2() { string source = @" public class A : System.Attribute { } public class Test { [field: System.Obsolete] [field: A] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(7, 6), // (8,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: A] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(8, 6), // (11,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete("obsolete", error: true)] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(11, 6) ); } [Fact] public void TestFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { public A(int i) { } } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { public B(int i) { } } public class Test { [field: A(1)] public int P { get; set; } [field: A(2)] public int P2 { get; } [B(3)] [field: A(33)] public int P3 { get; } [property: B(4)] [field: A(44)] [field: A(444)] public int P4 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); Assert.Null(prop2.SetMethod); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(2)" }), GetAttributeStrings(field2.GetAttributes())); var prop3 = @class.GetMember<PropertySymbol>("P3"); Assert.Equal("B(3)", prop3.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop3.SetMethod); var field3 = @class.GetMember<FieldSymbol>("<P3>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(33)" }), GetAttributeStrings(field3.GetAttributes())); var prop4 = @class.GetMember<PropertySymbol>("P4"); Assert.Equal("B(4)", prop4.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop4.SetMethod); var field4 = @class.GetMember<FieldSymbol>("<P4>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(44)", "A(444)" }), GetAttributeStrings(field4.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestGeneratedTupleAndDynamicAttributesOnAutoProperty() { string source = @" public class Test { public (dynamic a, int b) P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { Assert.Empty(field1.GetAttributes()); } else { var dynamicAndTupleNames = new[] { "System.Runtime.CompilerServices.DynamicAttribute({false, true, false})", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})" }; AssertEx.SetEqual(s_backingFieldAttributes.Concat(dynamicAndTupleNames), GetAttributeStrings(field1.GetAttributes())); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_SpecialName() { string source = @" public struct Test { [field: System.Runtime.CompilerServices.SpecialName] public static int P { get; set; } public static int P2 { get; set; } [field: System.Runtime.CompilerServices.SpecialName] public static int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.HasSpecialName); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.HasSpecialName); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_NonSerialized() { string source = @" public class Test { [field: System.NonSerialized] public int P { get; set; } public int P2 { get; set; } [field: System.NonSerialized] public int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.IsNotSerialized); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.IsNotSerialized); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } Assert.True(field3.IsNotSerialized); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(0)] public static int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS0637: The FieldOffset attribute is not allowed on static or const fields // [field: System.Runtime.InteropServices.FieldOffset(0)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadField, "System.Runtime.InteropServices.FieldOffset").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset2() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(-1)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0591: Invalid value for argument to 'System.Runtime.InteropServices.FieldOffset' attribute // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "-1").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 56), // (4,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset3() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Auto)] public class Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(7, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset4() { string source = @" using System.Runtime.InteropServices; public struct Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(6, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset5() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct Test { public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,16): error CS0625: 'Test.P': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int P { get; set; } Diagnostic(ErrorCode.ERR_MissingStructOffset, "P").WithArguments("Test.P").WithLocation(7, 16) ); } [Fact] public void TestWellKnownAttributeOnProperty_FixedBuffer() { string source = @" public class Test { [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS8362: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property // [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty, "System.Runtime.CompilerServices.FixedBuffer").WithLocation(4, 13) ); } [ConditionalFact(typeof(DesktopOnly))] public void TestWellKnownAttributeOnProperty_DynamicAttribute() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DynamicAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS1970: Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead. // [field: System.Runtime.CompilerServices.DynamicAttribute()] Diagnostic(ErrorCode.ERR_ExplicitDynamicAttr, "System.Runtime.CompilerServices.DynamicAttribute()").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsReadOnlyAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsReadOnlyAttribute()").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsByRefLikeAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsByRefLikeAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsByRefLikeAttribute()").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_DateTimeConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public System.DateTime P { get; set; } [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public int P2 { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_DecimalConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal P { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public int P2 { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal field; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; var constantExpected = "1844674407800451891300"; string[] decimalAttributeExpected = new[] { "System.Runtime.CompilerServices.DecimalConstantAttribute(0, 0, 100, 100, 100)" }; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field1.GetAttributes())); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field1.GetAttributes())); Assert.Equal(constantExpected, field1.ConstantValue.ToString()); } var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field2.GetAttributes())); var field3 = @class.GetMember<FieldSymbol>("field"); if (isFromSource) { AssertEx.SetEqual(decimalAttributeExpected, GetAttributeStrings(field3.GetAttributes())); } else { Assert.Empty(GetAttributeStrings(field3.GetAttributes())); Assert.Equal(constantExpected, field3.ConstantValue.ToString()); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_TupleElementNamesAttribute() { string source = @" namespace System.Runtime.CompilerServices { public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class Test { [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })] public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (11,13): error CS8138: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { "hello" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })").WithLocation(11, 13) ); } [Fact] public void TestWellKnownEarlyAttributeOnProperty_Obsolete() { string source = @" public class Test { [field: System.Obsolete] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.ObsoleteAttribute" }), GetAttributeStrings(field1.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field1.ObsoleteAttributeData.Kind); Assert.Null(field1.ObsoleteAttributeData.Message); Assert.False(field1.ObsoleteAttributeData.IsError); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { @"System.ObsoleteAttribute(""obsolete"", true)" }), GetAttributeStrings(field2.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field2.ObsoleteAttributeData.Kind); Assert.Equal("obsolete", field2.ObsoleteAttributeData.Message); Assert.True(field2.ObsoleteAttributeData.IsError); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestFieldAttributesOnProperty() { string source = @" public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(9, 6), // (6,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(6, 6) ); } [Fact] public void TestFieldAttributesOnPropertyAccessors() { string source = @" public class A : System.Attribute { } public class Test { public int P { [field: A] get => throw null; set => throw null; } public int P2 { [field: A] get; set; } public int P3 { [field: A] get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P { [field: A] get => throw null; set => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(6, 21), // (7,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P2 { [field: A] get; set; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(7, 22), // (8,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P3 { [field: A] get => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(8, 22) ); } [Fact] public void TestMultipleFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false) ] public class Single : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class Multiple : System.Attribute { } public class Test { [field: Single] [field: Single] [field: Multiple] [field: Multiple] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0579: Duplicate 'Single' attribute // [field: Single] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Single").WithArguments("Single").WithLocation(11, 13) ); } [Fact] public void TestInheritedFieldAttributesOnOverriddenProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, Inherited = true) ] public class A : System.Attribute { public A(int i) { } } public class Base { [field: A(1)] [A(2)] public virtual int P { get; set; } } public class Derived : Base { public override int P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var parent = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); bool isFromSource = parent is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = parent.GetMember<PropertySymbol>("P"); Assert.Equal("A(2)", prop1.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = parent.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var child = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var prop2 = child.GetMember<PropertySymbol>("P"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.SetMethod.GetAttributes())); var field2 = child.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestPropertyTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get; set; } [field: A] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(10, 13), // (7,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(7, 13) ); } [Fact] public void TestClassTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Class) ] public class ClassAllowed : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field) ] public class FieldAllowed : System.Attribute { } public class Test { [field: ClassAllowed] // error 1 [field: FieldAllowed] public int P { get; set; } [field: ClassAllowed] // error 2 [field: FieldAllowed] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(14, 13), // (10,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(10, 13) ); } [Fact] public void TestImproperlyTargetedFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } [field: A] public int P3 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(10, 6), // (13,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(13, 13), // (7,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(7, 6) ); } [Fact] public void TestAttributesOnEvents() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA] //in event decl public event System.Action E1; [event: BB] //in event decl public event System.Action E2; [method: CC] //in both accessors public event System.Action E3; [field: DD] //on field public event System.Action E4; [EE] //in event decl public event System.Action E5 { add { } remove { } } [event: FF] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG] add { } remove { } } //in accessor public event System.Action E8 { [method: HH] add { } remove { } } //in accessor public event System.Action E9 { [param: II] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ] add { } remove { } } //on return (after .param[0]) } "; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var event1 = @class.GetMember<EventSymbol>("E1"); var event2 = @class.GetMember<EventSymbol>("E2"); var event3 = @class.GetMember<EventSymbol>("E3"); var event4 = @class.GetMember<EventSymbol>("E4"); var event5 = @class.GetMember<EventSymbol>("E5"); var event6 = @class.GetMember<EventSymbol>("E6"); var event7 = @class.GetMember<EventSymbol>("E7"); var event8 = @class.GetMember<EventSymbol>("E8"); var event9 = @class.GetMember<EventSymbol>("E9"); var event10 = @class.GetMember<EventSymbol>("E10"); var accessorsExpected = isFromSource ? new string[0] : new[] { "CompilerGeneratedAttribute" }; Assert.Equal("AA", GetSingleAttributeName(event1)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event1.AssociatedField); Assert.Equal(0, event1.GetFieldAttributes().Length); } Assert.Equal("BB", GetSingleAttributeName(event2)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event2.AssociatedField); Assert.Equal(0, event2.GetFieldAttributes().Length); } AssertNoAttributes(event3); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event3.AssociatedField); Assert.Equal(0, event3.GetFieldAttributes().Length); } AssertNoAttributes(event4); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.RemoveMethod.GetAttributes())); if (isFromSource) { Assert.Equal("DD", GetSingleAttributeName(event4.AssociatedField)); Assert.Equal("DD", event4.GetFieldAttributes().Single().AttributeClass.Name); } Assert.Equal("EE", GetSingleAttributeName(event5)); AssertNoAttributes(event5.AddMethod); AssertNoAttributes(event5.RemoveMethod); Assert.Equal("FF", GetSingleAttributeName(event6)); AssertNoAttributes(event6.AddMethod); AssertNoAttributes(event6.RemoveMethod); AssertNoAttributes(event7); Assert.Equal("GG", GetSingleAttributeName(event7.AddMethod)); AssertNoAttributes(event7.RemoveMethod); AssertNoAttributes(event8); Assert.Equal("HH", GetSingleAttributeName(event8.AddMethod)); AssertNoAttributes(event8.RemoveMethod); AssertNoAttributes(event9); AssertNoAttributes(event9.AddMethod); AssertNoAttributes(event9.RemoveMethod); Assert.Equal("II", GetSingleAttributeName(event9.AddMethod.Parameters.Single())); AssertNoAttributes(event10); AssertNoAttributes(event10.AddMethod); AssertNoAttributes(event10.RemoveMethod); Assert.Equal("JJ", event10.AddMethod.GetReturnTypeAttributes().Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false)); } [Fact] public void TestAttributesOnEvents_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA(0)] //in event decl public event System.Action E1; [event: BB(0)] //in event decl public event System.Action E2; [method: CC(0)] //in both accessors public event System.Action E3; [field: DD(0)] //on field public event System.Action E4; [EE(0)] //in event decl public event System.Action E5 { add { } remove { } } [event: FF(0)] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) } "; CreateCompilation(source).VerifyDiagnostics( // (15,6): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // [AA(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (17,13): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [event: BB(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (19,14): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [method: CC(0)] //in both accessors Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (21,13): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [field: DD(0)] //on field Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (24,6): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"), // (26,13): error CS1729: 'FF' does not contain a constructor that takes 1 arguments // [event: FF(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "FF(0)").WithArguments("FF", "1"), // (29,38): error CS1729: 'GG' does not contain a constructor that takes 1 arguments // public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "GG(0)").WithArguments("GG", "1"), // (30,46): error CS1729: 'HH' does not contain a constructor that takes 1 arguments // public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "HH(0)").WithArguments("HH", "1"), // (31,45): error CS1729: 'II' does not contain a constructor that takes 1 arguments // public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "II(0)").WithArguments("II", "1"), // (32,47): error CS1729: 'JJ' does not contain a constructor that takes 1 arguments // public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "JJ(0)").WithArguments("JJ", "1"), // (22,32): warning CS0067: The event 'Test.E4' is never used // public event System.Action E4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("Test.E4"), // (18,32): warning CS0067: The event 'Test.E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("Test.E2"), // (20,32): warning CS0067: The event 'Test.E3' is never used // public event System.Action E3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("Test.E3"), // (16,32): warning CS0067: The event 'Test.E1' is never used // public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("Test.E1")); } [Fact] public void TestAttributesOnIndexer_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class Test { public int this[[AA(0)]int x] { [return: BB(0)] [CC(0)] get { return x; } [param: DD(0)] [EE(0)] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // public int this[[AA(0)]int x] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (13,10): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [CC(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (12,18): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [return: BB(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (16,17): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [param: DD(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (17,10): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1")); } private static string GetSingleAttributeName(Symbol symbol) { return symbol.GetAttributes().Single().AttributeClass.Name; } private static void AssertNoAttributes(Symbol symbol) { Assert.Equal(0, symbol.GetAttributes().Length); } [Fact] public void TestAttributesOnDelegates() { string source = @" using System; public class TypeAttribute : System.Attribute { } public class ParamAttribute : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute] [return: ReturnTypeAttribute] public delegate T Delegate<[TypeParamAttribute]T> ([ParamAttribute]T p1, [param: ParamAttribute]ref T p2, [ParamAttribute]out T p3); public delegate int Delegate2 ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate<int>).GetCustomAttributes(false); } }"; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeAttribute"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); var returnTypeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ReturnTypeAttribute"); var typeParamAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); Assert.Equal(1, delegateType.GetAttributes(typeAttrType).Count()); // Verify type parameter attribute var typeParameters = delegateType.TypeParameters; Assert.Equal(1, typeParameters.Length); Assert.Equal(1, typeParameters[0].GetAttributes(typeParamAttrType).Count()); // Verify delegate methods (return type/parameters) attributes // Invoke method // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax var invokeMethod = delegateType.GetMethod("Invoke"); Assert.Equal(1, invokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(typeParameters[0], invokeMethod.ReturnType); var parameters = invokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); // Delegate Constructor: // 1) Doesn't have any return type attributes // 2) Doesn't have any parameter attributes var ctor = delegateType.GetMethod(".ctor"); Assert.Equal(0, ctor.GetReturnTypeAttributes().Length); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: // 1) Doesn't have any return type attributes // 2) Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); Assert.Equal(0, beginInvokeMethod.GetReturnTypeAttributes().Length); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(5, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[4].GetAttributes(paramAttrType).Count()); // EndInvoke method: // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax // only for ref/out parameters. var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); Assert.Equal(1, endInvokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); parameters = endInvokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p2", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); } [Fact] public void TestAttributesOnDelegates_NoDuplicateDiagnostics() { string source = @" public class TypeAttribute : System.Attribute { } public class ParamAttribute1 : System.Attribute { } public class ParamAttribute2 : System.Attribute { } public class ParamAttribute3 : System.Attribute { } public class ParamAttribute4 : System.Attribute { } public class ParamAttribute5 : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute(0)] [return: ReturnTypeAttribute(0)] public delegate T Delegate<[TypeParamAttribute(0)]T> ([ParamAttribute1(0)]T p1, [param: ParamAttribute2(0)]ref T p2, [ParamAttribute3(0)]out T p3); public delegate int Delegate2 ([ParamAttribute4(0)]int p1 = 0, [param: ParamAttribute5(0)]params int[] p2); }"; CreateCompilation(source).VerifyDiagnostics( // (13,6): error CS1729: 'TypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeAttribute(0)").WithArguments("TypeAttribute", "1"), // (15,33): error CS1729: 'TypeParamAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeParamAttribute(0)").WithArguments("TypeParamAttribute", "1"), // (15,60): error CS1729: 'ParamAttribute1' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute1(0)").WithArguments("ParamAttribute1", "1"), // (15,93): error CS1729: 'ParamAttribute2' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute2(0)").WithArguments("ParamAttribute2", "1"), // (15,123): error CS1729: 'ParamAttribute3' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute3(0)").WithArguments("ParamAttribute3", "1"), // (14,14): error CS1729: 'ReturnTypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ReturnTypeAttribute(0)").WithArguments("ReturnTypeAttribute", "1"), // (17,37): error CS1729: 'ParamAttribute4' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute4(0)").WithArguments("ParamAttribute4", "1"), // (17,76): error CS1729: 'ParamAttribute5' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute5(0)").WithArguments("ParamAttribute5", "1")); } [Fact] public void TestAttributesOnDelegateWithOptionalAndParams() { string source = @" using System; public class ParamAttribute : System.Attribute { } class C { public delegate int Delegate ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate).GetCustomAttributes(false); } }"; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromMetadata => moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); // Verify delegate methods (return type/parameters) attributes // Invoke method has parameter attributes from delegate declaration syntax var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); var parameters = invokeMethod.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1]); } // Delegate Constructor: Doesn't have any parameter attributes var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(4, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify no ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1], expected: false); } }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(false), symbolValidator: symbolValidator(true)); } [Fact] public void TestAttributesOnEnumField() { string source = @" using System; using System.Collections.Generic; using System.Reflection; using CustomAttribute; using AN = CustomAttribute.AttrName; // Use AttrName without Attribute suffix [assembly: AN(UShortField = 4321)] [assembly: AN(UShortField = 1234)] // TODO: below attribute seems to be an ambiguous attribute specification // TODO: modify the test assembly to remove ambiguity // [module: AttrName(TypeField = typeof(System.IO.FileStream))] namespace AttributeTest { class Goo { public class NestedClass { // enum as object [AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly | BindingFlags.Public, UIntField = 123 * Field)] internal const uint Field = 10; } [AllInheritMultiple(new char[] { 'q', 'c' }, """")] [AllInheritMultiple()] enum NestedEnum { zero, one = 1, [AllInheritMultiple(null, 256, 0f, -1, AryField = new ulong[] { 0, 1, 12345657 })] [AllInheritMultipleAttribute(typeof(Dictionary<string, int>), 255 + NestedClass.Field, -0.0001f, 3 - (short)NestedEnum.oneagain)] three = 3, oneagain = one } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; var compilation = CreateCompilation(source, references, options: TestOptions.ReleaseDll); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var attrs = m.GetAttributes(); // Assert.Equal(1, attrs.Count); // Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); // attrs[0].VerifyValue<Type>(0, "TypeField", TypedConstantKind.Type, typeof(System.IO.FileStream)); var assembly = m.ContainingSymbol; attrs = assembly.GetAttributes(); Assert.Equal(2, attrs.Length); Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); attrs[1].VerifyNamedArgumentValue<ushort>(0, "UShortField", TypedConstantKind.Primitive, 1234); var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var top = (NamedTypeSymbol)ns.GetMember("Goo"); var type = top.GetMember<NamedTypeSymbol>("NestedClass"); var field = type.GetMember<FieldSymbol>("Field"); attrs = field.GetAttributes(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs[0].AttributeClass.ToDisplayString()); attrs[0].VerifyValue(0, TypedConstantKind.Enum, (int)FileMode.Open); attrs[0].VerifyValue(1, TypedConstantKind.Enum, (int)(BindingFlags.DeclaredOnly | BindingFlags.Public)); attrs[0].VerifyNamedArgumentValue<uint>(0, "UIntField", TypedConstantKind.Primitive, 1230); var nenum = top.GetMember<TypeSymbol>("NestedEnum"); attrs = nenum.GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Array, new char[] { 'q', 'c' }); Assert.Equal(SyntaxKind.Attribute, attrs[0].ApplicationSyntaxReference.GetSyntax().Kind()); var syntax = (AttributeSyntax)attrs[0].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(2, syntax.ArgumentList.Arguments.Count()); syntax = (AttributeSyntax)attrs[1].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(0, syntax.ArgumentList.Arguments.Count()); attrs = nenum.GetMember("three").GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs[0].VerifyValue<long>(1, TypedConstantKind.Primitive, 256); attrs[0].VerifyValue<float>(2, TypedConstantKind.Primitive, 0); attrs[0].VerifyValue<short>(3, TypedConstantKind.Primitive, -1); attrs[0].VerifyNamedArgumentValue<ulong[]>(0, "AryField", TypedConstantKind.Array, new ulong[] { 0, 1, 12345657 }); attrs[1].VerifyValue<object>(0, TypedConstantKind.Type, typeof(Dictionary<string, int>)); attrs[1].VerifyValue<long>(1, TypedConstantKind.Primitive, 265); attrs[1].VerifyValue<float>(2, TypedConstantKind.Primitive, -0.0001f); attrs[1].VerifyValue<short>(3, TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesOnDelegate() { string source = @" using System; using System.Collections.Generic; using CustomAttribute; namespace AttributeTest { public class Goo { [AllInheritMultiple(new object[] { 0, """", null }, 255, -127 - 1, AryProp = new object[] { new object[] { """", typeof(IList<string>) } })] public delegate void NestedSubDele([AllInheritMultiple()]string p1, [Derived(typeof(string[, ,]))]string p2); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var dele = (NamedTypeSymbol)type.GetTypeMember("NestedSubDele"); var attrs = dele.GetAttributes(); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 0, "", null }); attrs.First().VerifyValue<byte>(1, TypedConstantKind.Primitive, 255); attrs.First().VerifyValue<sbyte>(2, TypedConstantKind.Primitive, -128); attrs.First().VerifyNamedArgumentValue<object[]>(0, "AryProp", TypedConstantKind.Array, new object[] { new object[] { "", typeof(IList<string>) } }); var mem = dele.GetMember<MethodSymbol>("Invoke"); attrs = mem.Parameters[0].GetAttributes(); Assert.Equal(1, attrs.Length); attrs = mem.Parameters[1].GetAttributes(); Assert.Equal(1, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Type, typeof(string[,,])); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesUseBaseAttributeField() { string source = @" using System; namespace AttributeTest { public interface IGoo { [CustomAttribute.Derived(new object[] { 1, null, ""Hi"" }, ObjectField = 2)] int F(int p); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetMember<MethodSymbol>("F").GetAttributes(); Assert.Equal(@"CustomAttribute.DerivedAttribute({1, null, ""Hi""}, ObjectField = 2)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 1, null, "Hi" }); attrs.First().VerifyNamedArgumentValue<object>(0, "ObjectField", TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007a() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Z { public class Attr { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007b() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } public class Attr : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007c() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute /*: Attribute*/ { } } namespace Y { public class AttrAttribute /*: Attribute*/ { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007d() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Y { public class AttrAttribute : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); var syntax = attrs.Single().ApplicationSyntaxReference.GetSyntax(); Assert.NotNull(syntax); Assert.IsType<AttributeSyntax>(syntax); CompileAndVerify(compilation).VerifyDiagnostics(); } [Fact] public void TestAttributesWithParamArrayInCtor01() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' '}, """")] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributesWithParamArrayInCtor02() { string source = @" using System; namespace AttributeTest { class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } class Program { [Example(""MultipleArgumentsToParamsParameter"", 4, 5, 6)] public void MultipleArgumentsToParamsParameter() { } [Example(""NoArgumentsToParamsParameter"")] public void NoArgumentsToParamsParameter() { } [Example(""NullArgumentToParamsParameter"", null)] public void NullArgumentToParamsParameter() { } static void Main() { ExampleAttribute att = null; try { var programType = typeof(Program); var method = programType.GetMember(""MultipleArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NoArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NullArgumentToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } } "; Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeClass = (NamedTypeSymbol)ns.GetMember("ExampleAttribute"); var method = (MethodSymbol)type.GetMember("MultipleArgumentsToParamsParameter"); var attrs = method.GetAttributes(attributeClass); var attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "MultipleArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { 4, 5, 6 }); method = (MethodSymbol)type.GetMember("NoArgumentsToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NoArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { }); method = (MethodSymbol)type.GetMember("NullArgumentToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NullArgumentToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. var compVerifier = CompileAndVerify( source, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator, expectedOutput: "True\r\n", expectedSignatures: new[] { Signature("AttributeTest.Program", "MultipleArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"MultipleArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void MultipleArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NoArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NoArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void NoArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NullArgumentToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NullArgumentToParamsParameter\", )] public hidebysig instance System.Void NullArgumentToParamsParameter() cil managed"), }); } [Fact, WorkItem(531385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531385")] public void TestAttributesWithParamArrayInCtor3() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' ' }, new string[] { ""whatever"" })] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributeSpecifiedOnItself() { string source = @" using System; namespace AttributeTest { [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("MyAttribute"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Type, typeof(Object)); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesWithEnumArrayInCtor() { string source = @" using System; namespace AttributeTest { public enum X { a, b }; public class Y : Attribute { public int f; public Y(X[] x) { } } [Y(A.x)] public class A { public const X[] x = null; public static void Main() { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Array, (object[])null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541058")] [Fact] public void TestAttributesWithTypeof() { string source = @" using System; [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } "; CompileAndVerify(source); } [WorkItem(541071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541071")] [Fact] public void TestAttributesWithParams() { string source = @" using System; class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } [Example(""wibble"", 4, 5, 6)] class Program { static void Main() { ExampleAttribute att = null; try { att = (ExampleAttribute)typeof(Program).GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } "; var expectedOutput = @"True"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestAttributesOnReturnType() { string source = @" using System; using CustomAttribute; namespace AttributeTest { public class Goo { int p; public int Property { [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] get { return p; } [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] set { p = value; } } [return: AllInheritMultipleAttribute()] [return: AllInheritMultipleAttribute()] public int Method() { return p; } [return: AllInheritMultipleAttribute()] public delegate void Delegate(); public static void Main() {} } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var property = (PropertySymbol)type.GetMember("Property"); var getter = property.GetMethod; var attrs = getter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var setter = property.SetMethod; attrs = setter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var method = (MethodSymbol)type.GetMember("Method"); attrs = method.GetReturnTypeAttributes(); Assert.Equal(2, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); attr = attrs.Last(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var delegateType = type.GetTypeMember("Delegate"); var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); attrs = invokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); attrs = ctor.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); attrs = beginInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); attrs = endInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541397")] [Fact] public void TestAttributeWithSameNameAsTypeParameter() { string source = @" using System; namespace AttributeTest { public class TAttribute : Attribute { } public class RAttribute : TAttribute { } public class GClass<T> { [T] public enum E { } [R] internal R M<R>() { return default(R); } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("GClass"); var enumType = (NamedTypeSymbol)type.GetTypeMember("E"); var attributeType = (NamedTypeSymbol)ns.GetMember("TAttribute"); var attributeType2 = (NamedTypeSymbol)ns.GetMember("RAttribute"); var genMethod = (MethodSymbol)type.GetMember("M"); var attrs = enumType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs = genMethod.GetAttributes(attributeType2); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void TestAttributeWithVarIdentifierName() { string source = @" using System; namespace AttributeTest { public class var: Attribute { } [var] class Program { public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeType = (NamedTypeSymbol)ns.GetMember("var"); var attrs = type.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.var", attr.ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentBind_PropertyWithSameName() { var source = @"using System; namespace AttributeTest { class TestAttribute : Attribute { public TestAttribute(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class TestClass { ProtectionLevel ProtectionLevel { get { return ProtectionLevel.Privacy; } } [TestAttribute(ProtectionLevel.Privacy)] public int testField; } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeType = (NamedTypeSymbol)ns.GetMember("TestAttribute"); var field = (FieldSymbol)type.GetMember("testField"); var attrs = field.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541709")] [Fact] public void AttributeOnSynthesizedParameterSymbol() { var source = @"using System; namespace AttributeTest { public class TestAttributeForMethod : System.Attribute { } public class TestAttributeForParam : System.Attribute { } public class TestAttributeForReturn : System.Attribute { } class TestClass { int P1 { [TestAttributeForMethod] [param: TestAttributeForParam] [return: TestAttributeForReturn] set { } } int P2 { [TestAttributeForMethod] [return: TestAttributeForReturn] get { return 0; } } public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeTypeForMethod = (NamedTypeSymbol)ns.GetMember("TestAttributeForMethod"); var attributeTypeForParam = (NamedTypeSymbol)ns.GetMember("TestAttributeForParam"); var attributeTypeForReturn = (NamedTypeSymbol)ns.GetMember("TestAttributeForReturn"); var property = (PropertySymbol)type.GetMember("P1"); var setter = property.SetMethod; var attrs = setter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); Assert.Equal(1, setter.ParameterCount); attrs = setter.Parameters[0].GetAttributes(attributeTypeForParam); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForParam", attr.AttributeClass.ToDisplayString()); attrs = setter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); property = (PropertySymbol)type.GetMember("P2"); var getter = property.GetMethod; attrs = getter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); attrs = getter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributeStringForEnumTypedConstant() { var source = CreateCompilationWithMscorlib40(@" using System; namespace AttributeTest { enum X { One = 1, Two = 2, Three = 3 }; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event, Inherited = false, AllowMultiple = true)] class A : System.Attribute { public A(X x) { } public static void Main() { } // AttributeData.ToString() should display 'X.Three' not 'X.One | X.Two' [A(X.Three)] int field; // AttributeData.ToString() should display '5' [A((X)5)] int field2; } } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue(0, TypedConstantKind.Enum, (int)(AttributeTargets.Field | AttributeTargets.Event)); Assert.Equal(2, attr.CommonNamedArguments.Length); attr.VerifyNamedArgumentValue(0, "Inherited", TypedConstantKind.Primitive, false); attr.VerifyNamedArgumentValue(1, "AllowMultiple", TypedConstantKind.Primitive, true); Assert.Equal(@"System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Event, Inherited = false, AllowMultiple = true)", attr.ToString()); var fieldSymbol = (FieldSymbol)type.GetMember("field"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(AttributeTest.X.Three)", attrs.First().ToString()); fieldSymbol = (FieldSymbol)type.GetMember("field2"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(5)", attrs.First().ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesWithNamedConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(y:4, z:5, X = 6)] public class A : Attribute { public int X; public A(int y, int z) { Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithNamedConstructorArguments_02() { string source = @" using System; namespace AttributeTest { [A(3, z:5, y:4, X = 6)] public class A : Attribute { public int X; public A(int x, int y, int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541864")] [Fact] public void Bug_8769_TestAttributesWithNamedConstructorArguments() { string source = @" using System; namespace AttributeTest { [A(y: 1, x: 2)] public class A : Attribute { public A(int x, int y) { Console.WriteLine(x); Console.WriteLine(y); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(2, attrs.First().CommonConstructorArguments.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 1); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2 1 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithOptionalConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(3, z:5, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541861")] [Fact] public void Bug_8768_TestAttributesWithOptionalConstructorArguments() { string source = @" using System; namespace AttributeTest { [A] public class A : Attribute { public A(int x = 2) { Console.Write(x); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 2); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2"; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541854")] [Fact] public void Bug8761_StringArrayArgument() { var source = @"using System; [A(X = new string[] { """" })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void Bug8763_NullInArrayInitializer() { var source = @"using System; [A(X = new object[] { null })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); } } [A(X = new object[] { typeof(int), typeof(System.Type), 1, null, ""hi"" })] public class B { public object[] X; } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void AttributeArrayTypeArgument() { var source = @"using System; [A(objArray = new string[] { ""a"", null })] public class A : Attribute { public object[] objArray; public object obj; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); typeof(C).GetCustomAttributes(false); typeof(D).GetCustomAttributes(false); typeof(E).GetCustomAttributes(false); typeof(F).GetCustomAttributes(false); typeof(G).GetCustomAttributes(false); typeof(H).GetCustomAttributes(false); typeof(I).GetCustomAttributes(false); } } [A(objArray = new object[] { ""a"", null, 3 })] public class B { } /* CS0029: Cannot implicitly convert type 'int[]' to 'object[]' [A(objArray = new int[] { 3 })] public class Error { } */ [A(objArray = null)] public class C { } [A(obj = new string[] { ""a"" })] public class D { } [A(obj = new object[] { ""a"", null, 3 })] public class E { } [A(obj = new int[] { 1 })] public class F { } [A(obj = 1)] public class G { } [A(obj = ""a"")] public class H { } [A(obj = null)] public class I { } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541859")] [Fact] public void Bug8766_AttributeCtorOverloadResolution() { var source = @"using System; [A(C)] public class A : Attribute { const int C = 1; A(int x) { Console.Write(""int""); } public A(long x) { Console.Write(""long""); } static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: "int"); } [WorkItem(541876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541876")] [Fact] public void Bug8771_AttributeArgumentNameBinding() { var source = @"using System; public class A : Attribute { public A(int x) { Console.WriteLine(x); } } class B { const int X = 1; [A(X)] class C<[A(X)] T> { const int X = 2; } static void Main() { typeof(C<>).GetCustomAttributes(false); typeof(C<>).GetGenericArguments()[0].GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); var typeParameters = cClass.TypeParameters; Assert.Equal(1, typeParameters.Length); attrs = typeParameters[0].GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); }; string expectedOutput = @"2 2 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithNestedUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>.C))] public class B<T> { public class C { } } public class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, cClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>))] public class B<T> { } class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, bClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(542223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542223")] [Fact] public void AttributeArgumentAsEnumFromMetadata() { var metadataStream1 = CSharpCompilation.Create("bar.dll", references: new[] { MscorlibRef }, syntaxTrees: new[] { Parse("public enum Bar { Baz }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref1 = MetadataReference.CreateFromStream(metadataStream1); var metadataStream2 = CSharpCompilation.Create("goo.dll", references: new[] { MscorlibRef, ref1 }, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree( "public class Ca : System.Attribute { public Ca(object o) { } } " + "[Ca(Bar.Baz)]" + "public class Goo { }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref2 = MetadataReference.CreateFromStream(metadataStream2); var compilation = CSharpCompilation.Create("moo.dll", references: new[] { MscorlibRef, ref1, ref2 }); var goo = compilation.GetTypeByMetadataName("Goo"); var ca = goo.GetAttributes().First().CommonConstructorArguments.First(); Assert.Equal("Bar", ca.Type.Name); } [WorkItem(542318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542318")] [Fact] public void AttributeWithDaysOfWeekArgument() { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintaining compatibility with it. var source = @"using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(X = new DayOfWeek())] [A(X = new bool())] [A(X = new sbyte())] [A(X = new byte())] [A(X = new short())] [A(X = new ushort())] [A(X = new int())] [A(X = new uint())] [A(X = new char())] [A(X = new float())] [A(X = new Single())] [A(X = new double())] public class A : Attribute { public object X; const DayOfWeek dayofweek = new DayOfWeek(); const bool b = new bool(); const sbyte sb = new sbyte(); const byte by = new byte(); const short s = new short(); const ushort us = new ushort(); const int i = new int(); const uint ui = new uint(); const char c = new char(); const float f = new float(); const Single si = new Single(); const double d = new double(); public static void Main() { typeof(A).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(12, attrs.Count()); var enumerator = attrs.GetEnumerator(); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Enum, (int)new DayOfWeek()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new bool()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new sbyte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new byte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new short()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new ushort()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new int()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new uint()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new char()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new float()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new Single()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new double()); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration() { var source = @" using System; class A : Attribute { } partial class Program { [A] static partial void Goo(); static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration_02() { var source1 = @" using System; class A1 : Attribute {} class B1 : Attribute {} class C1 : Attribute {} class D1 : Attribute {} class E1 : Attribute {} partial class Program { [A1] [return: B1] static partial void Goo<[C1] T, [D1] U>([E1]int x); } "; var source2 = @" using System; class A2 : Attribute {} class B2 : Attribute {} class C2 : Attribute {} class D2 : Attribute {} class E2 : Attribute {} partial class Program { [A2] [return: B2] static partial void Goo<[C2] U, [D2] T>([E2]int y) { } static void Main() {} } "; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var programClass = m.GlobalNamespace.GetTypeMember("Program"); var gooMethod = (MethodSymbol)programClass.GetMember("Goo"); TestAttributeOnPartialMethodHelper(m, gooMethod); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } private void TestAttributeOnPartialMethodHelper(ModuleSymbol m, MethodSymbol gooMethod) { var a1Class = m.GlobalNamespace.GetTypeMember("A1"); var a2Class = m.GlobalNamespace.GetTypeMember("A2"); var b1Class = m.GlobalNamespace.GetTypeMember("B1"); var b2Class = m.GlobalNamespace.GetTypeMember("B2"); var c1Class = m.GlobalNamespace.GetTypeMember("C1"); var c2Class = m.GlobalNamespace.GetTypeMember("C2"); var d1Class = m.GlobalNamespace.GetTypeMember("D1"); var d2Class = m.GlobalNamespace.GetTypeMember("D2"); var e1Class = m.GlobalNamespace.GetTypeMember("E1"); var e2Class = m.GlobalNamespace.GetTypeMember("E2"); Assert.Equal(1, gooMethod.GetAttributes(a1Class).Count()); Assert.Equal(1, gooMethod.GetAttributes(a2Class).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b1Class, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b2Class, TypeCompareKind.ConsiderEverything2)).Count()); var typeParam1 = gooMethod.TypeParameters[0]; Assert.Equal(1, typeParam1.GetAttributes(c1Class).Count()); Assert.Equal(1, typeParam1.GetAttributes(c2Class).Count()); var typeParam2 = gooMethod.TypeParameters[1]; Assert.Equal(1, typeParam2.GetAttributes(d1Class).Count()); Assert.Equal(1, typeParam2.GetAttributes(d2Class).Count()); var param = gooMethod.Parameters[0]; Assert.Equal(1, param.GetAttributes(e1Class).Count()); Assert.Equal(1, param.GetAttributes(e2Class).Count()); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_Type() { var source1 = @" using System; class A : Attribute {} [A] partial class X {}"; var source2 = @" using System; class B : Attribute {} [B] partial class X {} class C { public static void Main() { typeof(X).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("X"); Assert.Equal(2, type.GetAttributes().Length); Assert.Equal(1, type.GetAttributes(aClass).Count()); Assert.Equal(1, type.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_TypeParam() { var source1 = @" using System; class A : Attribute {} partial class Gen<[A] T> {}"; var source2 = @" using System; class B : Attribute {} partial class Gen<[B] T> {} class C { public static void Main() {} }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("Gen"); var typeParameter = type.TypeParameters.First(); Assert.Equal(2, typeParameter.GetAttributes().Length); Assert.Equal(1, typeParameter.GetAttributes(aClass).Count()); Assert.Equal(1, typeParameter.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542550")] [Fact] public void Bug9824() { var source = @" using System; public class TAttribute : Attribute { public static void Main () {} } [T] public class GClass<T> where T : Attribute { [T] public enum E { } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("TAttribute"); NamedTypeSymbol GClass = m.GlobalNamespace.GetTypeMember("GClass").AsUnboundGenericType(); Assert.Equal(1, GClass.GetAttributes(attributeType).Count()); NamedTypeSymbol enumE = GClass.GetTypeMember("E"); Assert.Equal(1, enumE.GetAttributes(attributeType).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_01() { var source = @" using System; [A] public class A : Attribute { public A(object a = default(A)) { } } [A(1)] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 1); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_02() { var source = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class A : System.Attribute { public A(object o = null) { } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class B : System.Attribute { public B(object o = default(B)) { } } [A] [A(null)] [B] [B(default(B))] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeTypeA = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol attributeTypeB = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); // Verify A attributes var attrs = cClass.GetAttributes(attributeTypeA); Assert.Equal(2, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); // Verify B attributes attrs = cClass.GetAttributes(attributeTypeB); Assert.Equal(2, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(529044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529044")] [Fact] public void AttributeNameLookup() { var source = @" using System; public class MyClass<T> { } public class MyClassAttribute : Attribute { } [MyClass] public class Test { public static void Main() { typeof(Test).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("MyClassAttribute"); NamedTypeSymbol testClass = m.GlobalNamespace.GetTypeMember("Test"); // Verify attributes var attrs = testClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void Bug8956_NullArgumentToSystemTypeParam() { string source = @" using System; class A : Attribute { public A(System.Type t) {} } [A(null)] class Test { static void Main(string[] args) { typeof(Test).GetCustomAttributes(false); } } "; CompileAndVerify(source); } [Fact] public void SpecialNameAttributeFromSource() { string source = @" using System; using System.Runtime.CompilerServices; [SpecialName()] public struct S { [SpecialName] byte this[byte x] { get { return x; } } [SpecialName] public event Action<string> E; } "; var comp = CreateCompilation(source); var global = comp.SourceModule.GlobalNamespace; var typesym = global.GetMember("S") as NamedTypeSymbol; Assert.NotNull(typesym); Assert.True(typesym.HasSpecialName); var idxsym = typesym.GetMember(WellKnownMemberNames.Indexer) as PropertySymbol; Assert.NotNull(idxsym); Assert.True(idxsym.HasSpecialName); var etsym = typesym.GetMember("E") as EventSymbol; Assert.NotNull(etsym); Assert.True(etsym.HasSpecialName); } [WorkItem(546277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546277")] [Fact] public void TestArrayTypeInAttributeArgument() { var source = @"using System; public class W {} public class Y<T> { public class F {} public class Z<U> {} } public class X : Attribute { public X(Type y) { } } [X(typeof(W[]))] public class C1 {} [X(typeof(W[,]))] public class C2 {} [X(typeof(W[,][]))] public class C3 {} [X(typeof(Y<W>[][,]))] public class C4 {} [X(typeof(Y<int>.F[,][][,,]))] public class C5 {} [X(typeof(Y<int>.Z<W>[,][]))] public class C6 {} "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol classW = m.GlobalNamespace.GetTypeMember("W"); NamedTypeSymbol classY = m.GlobalNamespace.GetTypeMember("Y"); NamedTypeSymbol classF = classY.GetTypeMember("F"); NamedTypeSymbol classZ = classY.GetTypeMember("Z"); NamedTypeSymbol classX = m.GlobalNamespace.GetTypeMember("X"); NamedTypeSymbol classC1 = m.GlobalNamespace.GetTypeMember("C1"); NamedTypeSymbol classC2 = m.GlobalNamespace.GetTypeMember("C2"); NamedTypeSymbol classC3 = m.GlobalNamespace.GetTypeMember("C3"); NamedTypeSymbol classC4 = m.GlobalNamespace.GetTypeMember("C4"); NamedTypeSymbol classC5 = m.GlobalNamespace.GetTypeMember("C5"); NamedTypeSymbol classC6 = m.GlobalNamespace.GetTypeMember("C6"); var attrs = classC1.GetAttributes(); Assert.Equal(1, attrs.Length); var typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC2.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC3.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC4.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfW = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classYOfW), rank: 2); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC5.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfInt = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)))); NamedTypeSymbol substNestedF = classYOfInt.GetTypeMember("F"); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedF), rank: 3); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC6.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol substNestedZ = classYOfInt.GetTypeMember("Z").ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedZ)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void TestUnicodeAttributeArgument_Bug16353() { var source = @"using System; [Obsolete(UnicodeHighSurrogate)] class C { public const string UnicodeHighSurrogate = ""\uD800""; public const string UnicodeReplacementCharacter = ""\uFFFD""; static void Main() { string message = ((ObsoleteAttribute)typeof(C).GetCustomAttributes(false)[0]).Message; Console.WriteLine(message == UnicodeReplacementCharacter + UnicodeReplacementCharacter); } }"; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/41280")] public void TestUnicodeAttributeArgumentsStrings() { string HighSurrogateCharacter = "\uD800"; string LowSurrogateCharacter = "\uDC00"; string UnicodeReplacementCharacter = "\uFFFD"; string UnicodeLT0080 = "\u007F"; string UnicodeLT0800 = "\u07FF"; string UnicodeLT10000 = "\uFFFF"; string source = @" using System; public class C { public const string UnicodeSurrogate1 = ""\uD800""; public const string UnicodeSurrogate2 = ""\uD800\uD800""; public const string UnicodeSurrogate3 = ""\uD800\uDC00""; public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; [Obsolete(UnicodeSurrogate1)] public int x1; [Obsolete(UnicodeSurrogate2)] public int x2; [Obsolete(UnicodeSurrogate3)] public int x3; [Obsolete(UnicodeSurrogate4)] public int x4; [Obsolete(UnicodeSurrogate5)] public int x5; [Obsolete(UnicodeSurrogate6)] public int x6; [Obsolete(UnicodeSurrogate7)] public int x7; [Obsolete(UnicodeSurrogate8)] public int x8; [Obsolete(UnicodeSurrogate9)] public int x9; } "; Action<FieldSymbol, string> VerifyAttributes = (field, value) => { var attributes = field.GetAttributes(); Assert.Equal(1, attributes.Length); attributes[0].VerifyValue(0, TypedConstantKind.Primitive, value); }; Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol module) => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var x1 = type.GetMember<FieldSymbol>("x1"); var x2 = type.GetMember<FieldSymbol>("x2"); var x3 = type.GetMember<FieldSymbol>("x3"); var x4 = type.GetMember<FieldSymbol>("x4"); var x5 = type.GetMember<FieldSymbol>("x5"); var x6 = type.GetMember<FieldSymbol>("x6"); var x7 = type.GetMember<FieldSymbol>("x7"); var x8 = type.GetMember<FieldSymbol>("x8"); var x9 = type.GetMember<FieldSymbol>("x9"); // public const string UnicodeSurrogate1 = ""\uD800""; VerifyAttributes(x1, isFromSource ? HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate2 = ""\uD800\uD800""; VerifyAttributes(x2, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate3 = ""\uD800\uDC00""; VerifyAttributes(x3, HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; VerifyAttributes(x4, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; VerifyAttributes(x5, isFromSource ? HighSurrogateCharacter + UnicodeLT0080 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0080 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; VerifyAttributes(x6, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; VerifyAttributes(x7, isFromSource ? HighSurrogateCharacter + UnicodeLT10000 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT10000 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; VerifyAttributes(x8, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; VerifyAttributes(x9, isFromSource ? LowSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(546896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546896")] public void MissingTypeInSignature() { string lib1 = @" public enum E { A, B, C } "; string lib2 = @" public class A : System.Attribute { public A(E e) { } } public class C { [A(E.A)] public void M() { } } "; string main = @" class D : C { void N() { M(); } } "; var c1 = CreateCompilation(lib1); var r1 = c1.EmitToImageReference(); var c2 = CreateCompilation(lib2, references: new[] { r1 }); var r2 = c2.EmitToImageReference(); var cm = CreateCompilation(main, new[] { r2 }); cm.VerifyDiagnostics(); var model = cm.GetSemanticModel(cm.SyntaxTrees[0]); int index = main.IndexOf("M()", StringComparison.Ordinal); var m = (ExpressionSyntax)cm.SyntaxTrees[0].GetCompilationUnitRoot().FindToken(index).Parent.Parent; var info = model.GetSymbolInfo(m); var args = info.Symbol.GetAttributes()[0].CommonConstructorArguments; // unresolved type - parameter ignored Assert.Equal(0, args.Length); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")] public void NullArrays() { var source = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); }); } [Fact] public void NullTypeAndString() { var source = @" using System; public class A : Attribute { public A(Type t, string s) { } } [A(null, null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.Null(args[0].Value); Assert.Equal("Type", args[0].Type.Name); Assert.Throws<InvalidOperationException>(() => args[0].Values); Assert.Null(args[1].Value); Assert.Equal("String", args[1].Type.Name); Assert.Throws<InvalidOperationException>(() => args[1].Values); }); } [WorkItem(121, "https://github.com/dotnet/roslyn/issues/121")] [Fact] public void Bug_AttributeOnWrongGenericParameter() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; CompileAndVerify(source, symbolValidator: module => { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classTypeParameter = @class.TypeParameters.Single(); var method = @class.GetMember<MethodSymbol>("M"); var methodTypeParameter = method.TypeParameters.Single(); Assert.Empty(classTypeParameter.GetAttributes()); var attribute = methodTypeParameter.GetAttributes().Single(); Assert.Equal("XAttribute", attribute.AttributeClass.Name); }); } #endregion #region Error Tests [Fact] public void AttributeConstructorErrors1() { var compilation = CreateCompilationWithMscorlib40AndSystemCore(@" using System; static class m { public static int NotAConstant() { return 9; } } public enum e1 { a } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute() { } public XAttribute(decimal d) { } public XAttribute(ref int i) { } public XAttribute(e1 e) { } } [XDoesNotExist()] [X(1m)] [X(1)] [X(e1.a)] [X(A.dyn)] [X(m.NotAConstant() + 2)] class A { public const dynamic dyn = null; } ", options: TestOptions.ReleaseDll); // Note that the dev11 compiler produces errors that XDoesNotExist *and* XDoesNotExistAttribute could not be found. // It does not go on to produce the other errors. compilation.VerifyDiagnostics( // (33,2): error CS0246: The type or namespace name 'XDoesNotExistAttribute' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExistAttribute").WithLocation(33, 2), // (33,2): error CS0246: The type or namespace name 'XDoesNotExist' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExist").WithLocation(33, 2), // (34,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1m)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(34, 2), // (35,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(35, 2), // (37,2): error CS0121: The call is ambiguous between the following methods or properties: 'XAttribute.XAttribute(ref int)' and 'XAttribute.XAttribute(e1)' // [X(A.dyn)] Diagnostic(ErrorCode.ERR_AmbigCall, "X(A.dyn)").WithArguments("XAttribute.XAttribute(ref int)", "XAttribute.XAttribute(e1)").WithLocation(37, 2), // (38,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(m.NotAConstant() + 2)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(38, 2)); } [Fact] public void AttributeNamedArgumentErrors1() { var compilation = CreateCompilation(@" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public void F1(int i) { } private int PrivateField; public static int SharedProperty { get; set; } public int? ReadOnlyProperty { get { return null; } } public decimal BadDecimalType { get; set; } public System.DateTime BadDateType { get; set; } public Attribute[] BadArrayType { get; set; } } [X(NotFound = null)] [X(F1 = null)] [X(PrivateField = null)] [X(SharedProperty = null)] [X(ReadOnlyProperty = null)] [X(BadDecimalType = null)] [X(BadDateType = null)] [X(BadArrayType = null)] class A { } ", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (21,4): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // [X(NotFound = null)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound"), // (22,4): error CS0617: 'F1' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(F1 = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "F1").WithArguments("F1"), // (23,4): error CS0122: 'XAttribute.PrivateField' is inaccessible due to its protection level // [X(PrivateField = null)] Diagnostic(ErrorCode.ERR_BadAccess, "PrivateField").WithArguments("XAttribute.PrivateField"), // (24,4): error CS0617: 'SharedProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(SharedProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "SharedProperty").WithArguments("SharedProperty"), // (25,4): error CS0617: 'ReadOnlyProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(ReadOnlyProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ReadOnlyProperty").WithArguments("ReadOnlyProperty"), // (26,4): error CS0655: 'BadDecimalType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDecimalType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDecimalType").WithArguments("BadDecimalType"), // (27,4): error CS0655: 'BadDateType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDateType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDateType").WithArguments("BadDateType"), // (28,4): error CS0655: 'BadArrayType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadArrayType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadArrayType").WithArguments("BadArrayType")); } [Fact] public void AttributeNoMultipleAndInvalidTarget() { string source = @" using CustomAttribute; [Base(1)] [@BaseAttribute(""SOS"")] static class AttributeMod { [Derived('Q')] [Derived('C')] public class Goo { } [BaseAttribute(1)] [Base("""")] public class Bar { } }"; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'BaseAttribute' attribute // [@BaseAttribute("SOS")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "@BaseAttribute").WithArguments("BaseAttribute").WithLocation(4, 2), // (7,6): error CS0592: Attribute 'Derived' is not valid on this declaration type. It is only valid on 'struct, method, parameter' declarations. // [Derived('Q')] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Derived").WithArguments("Derived", "struct, method, parameter").WithLocation(7, 6), // (8,6): error CS0579: Duplicate 'Derived' attribute // [Derived('C')] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Derived").WithArguments("Derived").WithLocation(8, 6), // (13,6): error CS0579: Duplicate 'Base' attribute // [Base("")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Base").WithArguments("Base").WithLocation(13, 6)); } [Fact] public void AttributeAmbiguousSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Error: Ambiguous class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Refers to X class Class3 { } [@XAttribute] // Refers to XAttribute class Class4 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // [X] // Error: Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute").WithLocation(10, 2)); } [Fact] public void AttributeErrorVerbatimIdentifierInSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Refers to X class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Error: No attribute named X class Class3 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,2): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // [@X] // Error: No attribute named X Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@X").WithArguments("X").WithLocation(13, 2)); } [Fact] public void AttributeOpenTypeInAttribute() { string source = @" using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { public XAttribute(Type t) { } } class G<T> { [X(typeof(T))] T t1; // Error: open type in attribute [X(typeof(List<T>))] T t2; // Error: open type in attribute } class X { [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,8): error CS0416: 'T': an attribute argument cannot use type parameters // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(T)").WithArguments("T"), // (14,8): error CS0416: 'System.Collections.Generic.List<T>': an attribute argument cannot use type parameters // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(List<T>)").WithArguments("System.Collections.Generic.List<T>"), // (13,22): warning CS0169: The field 'G<T>.t1' is never used // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t1").WithArguments("G<T>.t1"), // (14,28): warning CS0169: The field 'G<T>.t2' is never used // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t2").WithArguments("G<T>.t2"), // (19,32): warning CS0169: The field 'X.x' is never used // [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("X.x"), // (20,29): warning CS0169: The field 'X.y' is never used // [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("X.y") ); } [WorkItem(540924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540924")] [Fact] public void AttributeEnumsAsAttributeParameters() { string source = @" using System; class EClass { public enum EEK { a, b, c, d }; } [AttributeUsage(AttributeTargets.Class)] internal class HelpAttribute : Attribute { public HelpAttribute(EClass.EEK[] b1) { } } [HelpAttribute(new EClass.EEK[2] { EClass.EEK.b, EClass.EEK.c })] public class MainClass { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifier() { string source = @" using System; // Below attribute specification generates a warning regarding invalid target specifier, // We skip binding the attribute with invalid target specifier, // no error generated for invalid use of AttributeUsage on non attribute class. [method: AttributeUsage(AttributeTargets.All)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type")); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifierOnInvalidAttribute() { string source = @" [method: OopsForgotToBindThis(Haha)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(/*CS0657, CS0246*/); } [Fact] public void AttributeUsageMultipleErrors() { string source = @"using System; class A { [AttributeUsage(AttributeTargets.Method)] void M1() { } [AttributeUsage(0)] void M2() { } } [AttributeUsage(0)] class B { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(4, 6), // (6,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. // [AttributeUsage(0)] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(6, 6), // (9,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(9, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { string source = @" using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(3, 39), // (3,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(3, 2) ); } [WorkItem(541059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541059")] [Fact] public void AttributeUsageIsNull() { string source = @" using System; [AttributeUsage(null)] public class Att1 : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } [WorkItem(541072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541072")] [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } /// <summary> /// Bug 7620: System.Nullreference Exception throws while the value of parameter AttributeUsage Is Null /// </summary> [Fact] public void CS1502ERR_NullAttributeUsageArgument() { string source = @" using System; [AttributeUsage(null)] public class Attr : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS1503: Argument 1: cannot convert from '<null>' to 'System.AttributeTargets' // [AttributeUsage(null)] Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } /// <summary> /// Bug 7632: Debug.Assert() Failure while Attribute Contains Generic /// </summary> [Fact] public void CS0404ERR_GenericAttributeError() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultipleSyntaxTrees() { var source1 = @"using System; [module: A] [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { }"; var source2 = @"[module: B]"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (2,10): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(2, 10), // (1,10): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 10)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultipleSyntaxTrees_TypeParam() { var source1 = @"using System; [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } class Gen<[A] T> {} "; var source2 = @"class Gen2<[B] T> {}"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (11,12): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. // class Gen<[A] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(11, 12), // (1,13): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // class Gen2<[B] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 13)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultiplePartialDeclarations() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } [A] partial class C { } [B] partial class C { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(10, 2), // (14,2): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 2)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultiplePartialDeclarations_TypeParam() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } partial class Gen<[A] T> { } partial class Gen<[B] T> { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,20): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. // partial class Gen<[A] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(11, 20), // (14,20): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // partial class Gen<[B] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 20)); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentError_CS0120() { var source = @"using System; class A : Attribute { public A(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class F { int ProtectionLevel; [A(ProtectionLevel.Privacy)] public int test; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,6): error CS0120: An object reference is required for the non-static field, method, or property 'F.ProtectionLevel' // [A(ProtectionLevel.Privacy)] Diagnostic(ErrorCode.ERR_ObjectRequired, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (14,7): warning CS0169: The field 'F.ProtectionLevel' is never used // int ProtectionLevel; Diagnostic(ErrorCode.WRN_UnreferencedField, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (17,14): warning CS0649: Field 'F.test' is never assigned to, and will always have its default value 0 // public int test; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "test").WithArguments("F.test", "0") ); } [Fact, WorkItem(541427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541427")] public void AttributeTargetsString() { var source = @" using System; [AttributeUsage(AttributeTargets.All & ~AttributeTargets.Class)] class A : Attribute { } [A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (3,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter' declarations. // [A] class C { } Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter") ); } [Fact] public void AttributeTargetsAssemblyModule() { var source = @" using System; [module: Attr()] [AttributeUsage(AttributeTargets.Assembly)] class Attr: Attribute { public Attr(){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,10): error CS0592: Attribute 'Attr' is not valid on this declaration type. It is only valid on 'assembly' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Attr").WithArguments("Attr", "assembly")); } [WorkItem(541259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541259")] [Fact] public void CS0182_NonConstantArrayCreationAttributeArgument() { var source = @"using System; [A(new int[1] {Program.f})] // error [A(new int[1])] // error [A(new int[1,1])] // error [A(new int[1 - 1])] // OK create an empty array [A(new A[0])] // error class Program { static public int f = 10; public static void Main() { typeof(Program).GetCustomAttributes(false); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1] {Program.f})] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Program.f"), // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1]"), // (5,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1,1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1,1]"), // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new A[0])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new A[0]")); } [WorkItem(541753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541753")] [Fact] public void CS0182_NestedArrays() { var source = @" using System; [A(new int[][] { new int[] { 1 } })] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[][] { new int[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[][] { new int[] { 1 } }").WithLocation(4, 4)); } [WorkItem(541849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541849")] [Fact] public void CS0182_MultidimensionalArrays() { var source = @"using System; class MyAttribute : Attribute { public MyAttribute(params int[][,] x) { } } [My] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,2): error CS0181: Attribute constructor parameter 'x' has type 'int[][*,*]', which is not a valid attribute parameter type // [My] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "int[][*,*]").WithLocation(8, 2)); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void AttributeDefaultValueArgument() { var source = @"using System; namespace AttributeTest { [A(3, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, object a = default(A)) { } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void CS0416_GenericAttributeDefaultValueArgument() { var source = @"using System; public class A : Attribute { public object X; static void Main() { typeof(C<int>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = default(E))] public enum E { } [A(X = typeof(E2))] public enum E2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = default(E))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(14, 12), // (17,12): error CS0416: 'C<T>.E2': an attribute argument cannot use type parameters // [A(X = typeof(E2))] Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(E2)").WithArguments("C<T>.E2").WithLocation(17, 12)); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void CS0246_VarAttributeIdentifier() { var source = @" [var()] class Program { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'varAttribute' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("varAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("var").WithLocation(2, 2)); } [Fact] public void TestAttributesWithInvalidArgumentsOrder() { string source = @" using System; namespace AttributeTest { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(3, z: 5, X = 6, y: 1)] [A(3, z: 5, 1)] [A(3, 1, X = 6, z: 5)] [A(X = 6, 0)] [A(X = 6, x: 0)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } public class B { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (7,27): error CS1016: Named attribute argument expected // [A(3, z: 5, X = 6, y: 1)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "1").WithLocation(7, 27), // (8,17): 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. // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "1").WithArguments("7.2").WithLocation(8, 17), // (8,11): error CS8321: Named argument 'z' is used out-of-position but is followed by an unnamed argument // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "z").WithArguments("z").WithLocation(8, 11), // (9,24): error CS1016: Named attribute argument expected // [A(3, 1, X = 6, z: 5)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "5").WithLocation(9, 24), // (10,15): error CS1016: Named attribute argument expected // [A(X = 6, 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(10, 15), // (11,18): error CS1016: Named attribute argument expected // [A(X = 6, x: 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(11, 18) ); } [WorkItem(541877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541877")] [Fact] public void Bug8772_TestDelegateAttributeNameBinding() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(Invoke)] delegate void F1(); delegate T F2<[A(Invoke)]T> (); const int Invoke = 1; static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // [A(Invoke)] Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(11, 8), // (14,22): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate T F2<[A(Invoke)]T> (); Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(14, 22)); } [Fact] public void AmbiguousAttributeErrors_01() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS1614: 'Description' is ambiguous between 'ValidWithoutSuffix.Description' and 'ValidWithSuffix.DescriptionAttribute'; use either '@Description' or 'DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Description").WithArguments("Description", "ValidWithoutSuffix.Description", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_02() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_03() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void AmbiguousAttributeErrors_04() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'ValidWithSuffix_And_ValidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "ValidWithSuffix_And_ValidWithoutSuffix.Description", "ValidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_05() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0616: 'InvalidWithoutSuffix.Description' is not an attribute class // [Description(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Description").WithArguments("InvalidWithoutSuffix.Description"), // (26,6): error CS0616: 'InvalidWithSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_06() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_06 { using InvalidWithSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_07() { string source = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0616: 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_08() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_08 { using InvalidWithSuffix; using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_09() { string source = @" namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_But_ValidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_09 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix_But_ValidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (31,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.Description' and 'InvalidWithoutSuffix_But_ValidWithSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_But_ValidWithoutSuffix.Description", "InvalidWithoutSuffix_But_ValidWithSuffix.Description"), // (34,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_10() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_10 { using ValidWithoutSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithoutSuffix.Description", "ValidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_11() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace TestNamespace_11 { using ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"), // (26,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_12() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_12 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AliasAttributeName() { var source = @"using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [A]class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,2): error CS1614: 'A' is ambiguous between 'A2' and 'A1'; use either '@A' or 'AAttribute' Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A").WithArguments("A", "A1", "A2").WithLocation(5, 2)); } [WorkItem(542279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542279")] [Fact] public void MethodSignatureAttributes() { var text = @"class A : System.Attribute { public A(object o) { } } class B { } class C { [return: A(new B())] static object F( [A(new B())] object x, [param: A(new B())] object y) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(8, 16), // (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(10, 12), // (11,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(11, 19)); } [Fact] public void AttributeDiagnosticsForEachArgument01() { var source = @"using System; public class A : Attribute { public A(object[] a) {} } [A(new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31) ); } [Fact] public void AttributeDiagnosticsForEachArgument02() { var source = @"using System; public class A : Attribute { public A(object[] a, object[] b) {} } [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; // Note that we suppress further errors once we have reported a bad attribute argument. CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31), // (7,60): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 60), // (7,72): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 72) ); } [Fact] public void AttributeArgumentDecimalTypeConstant() { var source = @"using System; [A(X = new decimal())] public class A : Attribute { public object X; const decimal y = new decimal(); }"; CreateCompilation(source).VerifyDiagnostics( // (2,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new decimal())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new decimal()").WithLocation(2, 8)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialClass() { string source = @" class A : System.Attribute { } partial class C<T> { } partial class C<[A][A] T> { } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(qq)] // CS0103 - no 'qq' in scope C(int qq) { } [A(rr)] // CS0103 - no 'rr' in scope void M(int rr) { } int P { [A(value)]set { } } // CS0103 - no 'value' in scope static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS0103: The name 'qq' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "qq").WithArguments("qq"), // (14,8): error CS0103: The name 'rr' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "rr").WithArguments("rr"), // (17,16): error CS0103: The name 'value' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "value").WithArguments("value")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>(); Assert.Equal(3, attrArgSyntaxes.Count()); foreach (var argSyntax in attrArgSyntaxes) { var info = semanticModel.GetSymbolInfo(argSyntax.Expression); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodTypeParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(typeof(T))] // CS0246 - no 'T' in scope void M<T>() { } static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "T").WithArguments("T")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var typeofSyntax = (TypeOfExpressionSyntax)attrArgSyntax.Expression; var typeofArgSyntax = typeofSyntax.Type; Assert.Equal("T", typeofArgSyntax.ToString()); var info = semanticModel.GetSymbolInfo(typeofArgSyntax); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnPartialMethod() { string source = @" class A : System.Attribute { } class B : System.Attribute { } partial class C { [return: B] [A] static partial void Goo(); [return: B] [A] static partial void Goo() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"), // error CS0579: Duplicate 'B' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"B").WithArguments("B")); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo<[A] T>(); static partial void Goo<[A] T>() { } // partial method without implementation, but another method with same name static partial void Goo2<[A] T>(); static void Goo2<[A] T>() { } // partial method without implementation, but another member with same name static partial void Goo3<[A] T>(); private int Goo3; // partial method without implementation static partial void Goo4<[A][A] T>(); // partial methods differing by signature static partial void Goo5<[A] T>(int x); static partial void Goo5<[A] T>(); // partial method without defining declaration static partial void Goo6<[A][A] T>() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6<T>()' // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6<T>()").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2<[A] T>() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,34): error CS0579: Duplicate 'A' attribute // static partial void Goo4<[A][A] T>(); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 34), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (7,30): error CS0579: Duplicate 'A' attribute // static partial void Goo<[A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(7, 30), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo([param: A]int y); static partial void Goo([A] int y) { } // partial method without implementation, but another method with same name static partial void Goo2([A] int y); static void Goo2([A] int y) { } // partial method without implementation, but another member with same name static partial void Goo3([A] int y); private int Goo3; // partial method without implementation static partial void Goo4([A][param: A] int y); // partial methods differing by signature static partial void Goo5([A] int y); static partial void Goo5([A] int y, int z); // partial method without defining declaration static partial void Goo6([A][A] int y) { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6(int)' // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6(int)").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2([A] int y) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,41): error CS0579: Duplicate 'A' attribute // static partial void Goo4([A][param: A] int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 41), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (6,37): error CS0579: Duplicate 'A' attribute // static partial void Goo([param: A]int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(6, 37), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [Fact] public void PartialMethodOverloads() { string source = @" class A : System.Attribute { } partial class C { static partial void F([A] int y); static partial void F(int y, [A]int z); } "; CompileAndVerify(source); } [WorkItem(543456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543456")] [Fact] public void StructLayoutFieldsAreUsed() { var source = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { int a, b, c; }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542662")] [Fact] public void FalseDuplicateOnPartial() { var source = @" using System; class A : Attribute { } partial class Program { static partial void Goo(int x); [A] static partial void Goo(int x) { } static partial void Goo(); [A] static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542652")] [Fact] public void Bug9958() { var source = @" class A : System.Attribute { } partial class C { static partial void Goo<T,[A] S>(); static partial void Goo<[A]>() { } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"), // (7,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo<>()' // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo").WithArguments("C.Goo<>()")); } [WorkItem(542909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542909")] [Fact] public void OverriddenPropertyMissingAccessor() { var source = @"using System; class A : Attribute { public virtual int P { get; set; } } class B1 : A { public override int P { get { return base.P; } } } class B2 : A { public override int P { set { } } } [A(P=0)] [B1(P=1)] [B2(P = 2)] class C { }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542899")] [Fact] public void TwoSyntaxTrees() { var source = @" using System.Reflection; [assembly: AssemblyTitle(""EnterpriseLibraryExtensions"")] "; var source2 = @" using Microsoft.Practices.EnterpriseLibrary.Configuration.Design; using EnterpriseLibraryExtensions; [assembly: ConfigurationDesignManager(typeof(ExtensionDesignManager))] "; var compilation = CreateCompilation(new string[] { source, source2 }); compilation.GetDiagnostics(); } [WorkItem(543785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543785")] [Fact] public void OpenGenericTypesUsedAsAttributeArgs() { var source = @" class Gen<T> { [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; }"; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); compilation.VerifyDiagnostics( // (4,6): error CS0246: The type or namespace name 'TypeAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttributeAttribute").WithLocation(4, 6), // (4,6): error CS0246: The type or namespace name 'TypeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttribute").WithLocation(4, 6), // (4,27): error CS0246: The type or namespace name 'L1' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L1").WithArguments("L1").WithLocation(4, 27), // (4,55): warning CS0649: Field 'Gen<T>.Fld6' is never assigned to, and will always have its default value // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld6").WithArguments("Gen<T>.Fld6", "").WithLocation(4, 55)); } [WorkItem(543914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543914")] [Fact] public void OpenGenericTypeInAttribute() { var source = @" class Gen<T> {} class Gen2<T>: System.Attribute {} [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,16): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class Gen2<T>: System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 16), // (5,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(6, 2)); } [Fact] public void OpenGenericTypeInAttributeWithGenericAttributeFeature() { var source = @" class Gen<T> {} class Gen2<T> : System.Attribute {} class Gen3<T> : System.Attribute { Gen3(T parameter) { } } [Gen] [Gen2] [Gen2()] [Gen2<U>] [Gen2<System.Collections.Generic.List<U>>] [Gen3(1)] public class Test<U> { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (6,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(6, 2), // (7,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(7, 2), // (8,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2()] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(8, 2), // (9,2): error CS8958: 'U': an attribute type argument cannot use type parameters // [Gen2<U>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<U>").WithArguments("U").WithLocation(9, 2), // (10,2): error CS8958: 'System.Collections.Generic.List<U>': an attribute type argument cannot use type parameters // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<System.Collections.Generic.List<U>>").WithArguments("System.Collections.Generic.List<U>").WithLocation(10, 2), // (10,2): error CS0579: Duplicate 'Gen2<>' attribute // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Gen2<System.Collections.Generic.List<U>>").WithArguments("Gen2<>").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'Gen3<T>' requires 1 type arguments // [Gen3(1)] Diagnostic(ErrorCode.ERR_BadArity, "Gen3").WithArguments("Gen3<T>", "type", "1").WithLocation(11, 2)); } [Fact] public void GenericAttributeTypeFromILSource() { var ilSource = @" .class public Gen<T> { } .class public Gen2<T> extends [mscorlib] System.Attribute { } "; var csharpSource = @" [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void Warnings_Unassigned_Unreferenced_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class B : Attribute { public Type PublicField; // CS0649 private Type PrivateField; // CS0169 protected Type ProtectedField; // CS0649 internal Type InternalField; // CS0649 }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,17): warning CS0649: Field 'B.PublicField' is never assigned to, and will always have its default value null // public Type PublicField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "PublicField").WithArguments("B.PublicField", "null"), // (8,18): warning CS0169: The field 'B.PrivateField' is never used // private Type PrivateField; // CS0169 Diagnostic(ErrorCode.WRN_UnreferencedField, "PrivateField").WithArguments("B.PrivateField"), // (9,20): warning CS0649: Field 'B.ProtectedField' is never assigned to, and will always have its default value null // protected Type ProtectedField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ProtectedField").WithArguments("B.ProtectedField", "null"), // (10,19): warning CS0649: Field 'B.InternalField' is never assigned to, and will always have its default value null // internal Type InternalField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "InternalField").WithArguments("B.InternalField", "null")); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void No_Warnings_For_Assigned_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public Type PublicField; // No CS0649 private Type PrivateField; // No CS0649 protected Type ProtectedField; // No CS0649 internal Type InternalField; // No CS0649 [A(PublicField = typeof(int))] [A(PrivateField = typeof(int))] [A(ProtectedField = typeof(int))] [A(InternalField = typeof(int))] static void Main() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,8): error CS0617: 'PrivateField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(PrivateField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "PrivateField").WithArguments("PrivateField"), // (14,8): error CS0617: 'ProtectedField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(ProtectedField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ProtectedField").WithArguments("ProtectedField"), // (15,8): error CS0617: 'InternalField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(InternalField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "InternalField").WithArguments("InternalField")); } [WorkItem(544351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544351")] [Fact] public void CS0182_ERR_BadAttributeArgument_Bug_12638() { var source = @" using System; [A(X = new Array[] { new[] { 1 } })] class A : Attribute { public object X; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new Array[] { new[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new Array[] { new[] { 1 } }").WithLocation(4, 8)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions() { var source = @"using System; [A((int)(object)""ABC"")] class A : Attribute { public A(int x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((int)(object)"ABC")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(int)(object)""ABC""").WithLocation(3, 4)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions_02() { var source = @"using System; [A((object[])(object)( new [] { 1 }))] class A : Attribute { public A(object[] x) { } } [B((object[])(object)(new string[] { ""a"", null }))] class B : Attribute { public B(object[] x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((object[])(object)( new [] { 1 }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(object[])(object)( new [] { 1 })").WithLocation(3, 4), // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [B((object[])(object)(new string[] { "a", null }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(object[])(object)(new string[] { ""a"", null })").WithLocation(9, 4)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue() { // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. var source = @" using System; class A : Attribute { public object X; } class C<T> { [A(X = C<T>.E.V)] public enum E { V } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = C<T>.E.V)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C<T>.E.V").WithLocation(11, 12)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void AttributeArgument_ConstructedType_ConstantValue() { // See comments for test CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue var source = @" using System; class A : Attribute { public object X; public static void Main() { typeof(C<>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } }"; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(544512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544512")] [Fact] public void LambdaInAttributeArg() { string source = @" public delegate void D(); public class myAttr : System.Attribute { public D d { get { return () => { }; } set { } } } [myAttr(d = () => { })] class X { public static int Main() { return 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): error CS0655: 'd' is not a valid named attribute argument because it is not a valid attribute parameter type // [myAttr(d = () => { })] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "d").WithArguments("d").WithLocation(14, 9)); } [WorkItem(544590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544590")] [Fact] public void LambdaInAttributeArg2() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public Goo(int sName) { } } public class Class1 { [field: Goo(((System.Func<int>)(() => 5))())] public event EventHandler Click; public static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [field: Goo(((System.Func<int>)(() => 5))())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "((System.Func<int>)(() => 5))()"), // (12,31): warning CS0067: The event 'Class1.Click' is never used // public event EventHandler Click; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("Class1.Click")); } [WorkItem(545030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545030")] [Fact] public void UserDefinedAttribute_Bug13264() { string source = @" namespace System.Runtime.InteropServices { [DllImport] // Error class DllImportAttribute {} } namespace System { [Object] // Warning public class Object : System.Attribute {} } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,6): error CS0616: 'System.Runtime.InteropServices.DllImportAttribute' is not an attribute class // [DllImport] // Error Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), // (9,6): warning CS0436: The type 'System.Object' in '' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // [Object] // Warning Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object")); } [WorkItem(545241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545241")] [Fact] public void ConditionalAttributeOnAttribute() { string source = @" using System; using System.Diagnostics; [Conditional(""A"")] class Attr1 : Attribute { } class Attr2 : Attribute { } class Attr3 : Attr1 { } [Attr1, Attr2, Attr3] class Test { } "; Action<ModuleSymbol> sourceValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(3, attrs.Length); }; Action<ModuleSymbol> metadataValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); // only one is not conditional Assert.Equal("Attr2", attrs.Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [WorkItem(545499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545499")] [Fact] public void IncompleteMethodParamAttribute() { string source = @" using System; public class MyAttribute2 : Attribute { public Type[] Types; } public class Test { public void goo([MyAttribute2(Types = new Type[ "; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); } [Fact, WorkItem(545556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545556")] public void NameLookupInDelegateParameterAttribute() { var source = @" using System; class A : Attribute { new const int Equals = 1; delegate void F([A(Equals)] int x); public A(int x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate void F([A(Equals)] int x); Diagnostic(ErrorCode.ERR_BadArgType, "Equals").WithArguments("1", "method group", "int")); } [Fact, WorkItem(546234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546234")] public void AmbiguousClassNamespaceLookup() { // One from source, one from PE var source = @" using System; [System] class System : Attribute { } "; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"), // (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'System' is a type not a namespace. Consider a 'using static' directive instead // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System").WithLocation(2, 7), // (4,16): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // class System : Attribute Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute"), // (3,2): error CS0616: 'System' is not an attribute class // [System] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); source = @" [assembly: X] namespace X { } "; var source2 = @" using System; public class X: Attribute { } "; var comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp0").ToMetadataReference(); CreateCompilationWithMscorlib40(source, references: new[] { comp1 }).VerifyDiagnostics( // (2,12): error CS0616: 'X' is not an attribute class // [assembly: X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, none from Source source2 = @" using System; public class X { } "; var source3 = @" namespace X { } "; var source4 = @" [X] class Y { } "; comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp1").ToMetadataReference(); var comp2 = CreateEmptyCompilation(source3, assemblyName: "Temp2").ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib40(source4, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0434: The namespace 'X' in 'Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'X' in 'Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // [X] Diagnostic(ErrorCode.ERR_SameFullNameNsAgg, "X").WithArguments("Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X", "Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X")); // Multiple from PE, one from Source: Failure var source5 = @" [X] class X { } "; comp3 = CreateCompilationWithMscorlib40(source5, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, one from Source: Success source5 = @" using System; [X] class X: Attribute { } "; CompileAndVerifyWithMscorlib40(source5, references: new[] { comp1, comp2 }); // Multiple from PE, multiple from Source var source6 = @" [X] class X { } namespace X { } "; comp3 = CreateCompilationWithMscorlib40(source6, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (3,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'X' // class X Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "X").WithArguments("X", "<global namespace>")); // Multiple from PE, one from Source with alias var source7 = @" using System; using X = Goo; [X] class Goo: Attribute { } "; comp3 = CreateCompilationWithMscorlib40(source7, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (4,2): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'X' // [X] Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "X").WithArguments("X", "<global namespace>"), // (4,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); } [Fact] public void AmbiguousClassNamespaceLookup_Container() { var source1 = @"using System; public class A : Attribute { } namespace N1 { public class B : Attribute { } public class C : Attribute { } }"; var comp = CreateCompilation(source1, assemblyName: "A"); var ref1 = comp.EmitToImageReference(); var source2 = @"using System; using N1; using N2; namespace N1 { class A : Attribute { } class B : Attribute { } } namespace N2 { class C : Attribute { } } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }, assemblyName: "B"); comp.VerifyDiagnostics( // (14,2): warning CS0436: The type 'B' in '' conflicts with the imported type 'B' in 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // [B] Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "B").WithArguments("", "N1.B", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N1.B").WithLocation(14, 2), // (15,2): error CS0104: 'C' is an ambiguous reference between 'N2.C' and 'N1.C' // [C] Diagnostic(ErrorCode.ERR_AmbigContext, "C").WithArguments("C", "N2.C", "N1.C").WithLocation(15, 2)); } [Fact] public void AmbiguousClassNamespaceLookup_Generic() { var source1 = @"public class A { } public class B<T> { } public class C<T, U> { }"; var comp = CreateCompilation(source1); var ref1 = comp.EmitToImageReference(); var source2 = @"class A<U> { } class B<U> { } class C<U> { } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }); comp.VerifyDiagnostics( // (4,2): error CS0616: 'A' is not an attribute class // [A] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "A").WithArguments("A").WithLocation(4, 2), // (5,2): error CS0616: 'B<U>' is not an attribute class // [B] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "B").WithArguments("B<U>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'C<U>' requires 1 type arguments // [C] Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<U>", "type", "1").WithLocation(6, 2)); } [WorkItem(546283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546283")] [Fact] public void ApplyIndexerNameAttributeTwice() { var source = @"using System.Runtime.CompilerServices; public class IA { [IndexerName(""ItemX"")] [IndexerName(""ItemY"")] public virtual int this[int index] { get { return 1;} set {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,3): error CS0579: Duplicate 'IndexerName' attribute // [IndexerName("ItemY")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "IndexerName").WithArguments("IndexerName").WithLocation(6, 3)); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal("ItemX", indexer.MetadataName); //First one wins. } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute1() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute2() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); // we now recognize the extension method even without the assembly-level attribute var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute3() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M")); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.False(method.TestIsExtensionBitTrue); Assert.False(method.IsExtensionMethod); } [WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")] [Fact] public void PEParameterSymbolParamArrayAttribute() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void Main(string[] args) { A.M(1, 2, 3); A.M(1, 2, 3, 4); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); var yParam = method.Parameters[1]; Assert.True(yParam.IsParams); Assert.Equal(0, yParam.GetAttributes().Length); } [WorkItem(546490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546490")] [Fact] public void Bug15984() { var source1 = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Goo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Goo::inc } // end of class Library1.Goo "; var reference1 = CompileIL(source1, prependDefaultHeader: false); var compilation = CreateCompilation("", new[] { reference1 }); var type = compilation.GetTypeByMetadataName("Library1.Goo"); Assert.Equal(0, type.GetAttributes()[0].ConstructorArguments.Count()); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void GenericAttributeType() { var source = @" using System; [A<>] // 1, 2 [A<int>] // 3, 4 [B] // 5 [B<>] // 6, 7 [B<int>] // 8, 9 [C] // 10 [C<>] // 11, 12 [C<int>] // 13, 14 [C<,>] // 15, 16 [C<int, int>] // 17, 18 class Test { } public class A : Attribute { } public class B<T> : Attribute // 19 { } public class C<T, U> : Attribute // 20 { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<>").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<>").WithArguments("generic attributes").WithLocation(7, 2), // (8,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<int>").WithArguments("generic attributes").WithLocation(8, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (10,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (11,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int>").WithArguments("generic attributes").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (12,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<,>").WithArguments("generic attributes").WithLocation(12, 2), // (13,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int, int>").WithArguments("generic attributes").WithLocation(13, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2), // (22,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class B<T> : Attribute // 19 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(22, 21), // (26,24): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T, U> : Attribute // 20 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(26, 24)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Source() { var source = @" using System; using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } public class C<T> : Attribute { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(12, 21), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(6, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(7, 2)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Metadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } "; // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. var comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(6, 2)); // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Nested() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [InnerAlias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "InnerAlias").WithArguments("generic attributes").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17), // (8,6): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_FeatureInPreview, "OuterAlias.Inner").WithArguments("generic attributes").WithLocation(8, 6)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17)); } [Fact] public void NestedWithGenericAttributeFeature() { var source = @" [Outer<int>.Inner] class Test { [Outer<int>.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void AliasedGenericAttributeType_NestedWithGenericAttributeFeature_IsAttribute() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void VerbatimAliasVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using ActionAttribute = A.ActionAttribute; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void DeclarationVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using A; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void Repro728865() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Microsoft.Yeti; namespace PFxIntegration { public class ProducerConsumerScenario { static void Main(string[] args) { Type program = typeof(ProducerConsumerScenario); MethodInfo methodInfo = program.GetMethod(""ProducerConsumer""); Object[] myAttributes = methodInfo.GetCustomAttributes(false); ; if (myAttributes.Length > 0) { Console.WriteLine(""\r\nThe attributes for the method - {0} - are: \r\n"", methodInfo); for (int j = 0; j < myAttributes.Length; j++) Console.WriteLine(""The type of the attribute is {0}"", myAttributes[j]); } } public enum CollectionType { Default, Queue, Stack, Bag } public ProducerConsumerScenario() { } [CartesianRowData( new int[] { 5, 100, 100000 }, new CollectionType[] { CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag })] public void ProducerConsumer(int inputSize, CollectionType collectionType) { Console.WriteLine(""Hello""); } } } namespace Microsoft.Yeti { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class CartesianRowDataAttribute : Attribute { public CartesianRowDataAttribute() { } public CartesianRowDataAttribute(params object[] data) { IEnumerable<object>[] asEnum = new IEnumerable<object>[data.Length]; for (int i = 0; i < data.Length; ++i) { WrapEnum((IEnumerable)data[i]); } } static void WrapEnum(IEnumerable x) { foreach (object a in x) { Console.WriteLine("" - "" + a + "" -""); } } } // class } // namespace "; CompileAndVerify(source, expectedOutput: @" - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer(Int32, CollectionType) - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute "); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument1() { var source = @" using System; public class Test { [ArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument2() { var source = @" using System; public class Test { [ParamArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ParamArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ParamArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } [ParamArrayOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [ParamArrayOrObjectAttribute(""A"")] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { "A" }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, "A"); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, "A"); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument3() { var source = @" using System; public class Test { [StringOnlyAttribute(new string[] { ""A"" })] [ObjectOnlyAttribute(new string[] { ""A"" })] //error [StringOrObjectAttribute(new string[] { ""A"" })] //string void M1() { } [StringOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [StringOrObjectAttribute(null)] //string void M2() { } //[StringOnlyAttribute(new object[] { ""A"" })] //overload resolution failure [ObjectOnlyAttribute(new object[] { ""A"" })] [StringOrObjectAttribute(new object[] { ""A"" })] //object void M3() { } [StringOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [StringOrObjectAttribute(""A"")] //string void M4() { } } public class StringOnlyAttribute : Attribute { public StringOnlyAttribute(params string[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class StringOrObjectAttribute : Attribute { public StringOrObjectAttribute(params string[] array) { } public StringOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ObjectOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ObjectOnlyAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (string[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { "A" }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument1() { var source = @" using System; public class Test { //[ArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument2() { var source = @" using System; public class Test { //[ParamArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ParamArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ParamArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } [ParamArrayOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [ParamArrayOrObjectAttribute(1)] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { 1 }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, 1); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, 1); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument3() { var source = @" using System; public class Test { [IntOnlyAttribute(new int[] { 1 })] [ObjectOnlyAttribute(new int[] { 1 })] [IntOrObjectAttribute(new int[] { 1 })] //int void M1() { } [IntOnlyAttribute(null)] [ObjectOnlyAttribute(null)] //[IntOrObjectAttribute(null)] //ambiguous void M2() { } //[IntOnlyAttribute(new object[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new object[] { 1 })] [IntOrObjectAttribute(new object[] { 1 })] //object void M3() { } [IntOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [IntOrObjectAttribute(1)] //int void M4() { } } public class IntOnlyAttribute : Attribute { public IntOnlyAttribute(params int[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class IntOrObjectAttribute : Attribute { public IntOrObjectAttribute(params int[] array) { } public IntOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, new object[] { value1 }); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); var value2 = (object[])null; attrs2[0].VerifyValue(0, TypedConstantKind.Array, value2); attrs2[1].VerifyValue(0, TypedConstantKind.Array, value2); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { 1 }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(739630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739630")] [Fact] public void NullVersusEmptyArray() { var source = @" using System; public class ArrayAttribute : Attribute { public int[] field; public ArrayAttribute(int[] param) { } } public class Test { [Array(null)] void M0() { } [Array(new int[] { })] void M1() { } [Array(null, field=null)] void M2() { } [Array(new int[] { }, field = null)] void M3() { } [Array(null, field = new int[] { })] void M4() { } [Array(new int[] { }, field = new int[] { })] void M5() { } static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var methods = Enumerable.Range(0, 6).Select(i => type.GetMember<MethodSymbol>("M" + i)); var attrs = methods.Select(m => m.GetAttributes().Single()).ToArray(); var nullArray = (int[])null; var emptyArray = new int[0]; const string fieldName = "field"; attrs[0].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[1].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[2].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[2].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[3].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[3].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[4].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[4].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); attrs[5].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[5].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); } [Fact] [WorkItem(530266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530266")] public void UnboundGenericTypeInTypedConstant() { var source = @" using System; public class TestAttribute : Attribute { public TestAttribute(Type x){} } [TestAttribute(typeof(Target<>))] class Target<T> {}"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); var typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); var comp2 = CreateCompilation("", new[] { comp.EmitToImageReference() }); type = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); Assert.IsAssignableFrom<PENamedTypeSymbol>(type); typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); } [Fact, WorkItem(1020038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020038")] public void Bug1020038() { var source1 = @" public class CTest {} "; var compilation1 = CreateCompilation(source1, assemblyName: "Bug1020038"); var source2 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(CTest))] class Test {} "; var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation2, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); var source3 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(System.Func<System.Action<CTest>>))] class Test {} "; var compilation3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation3, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); } [Fact, WorkItem(937575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937575"), WorkItem(121, "CodePlex")] public void Bug937575() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(compilation, symbolValidator: (m) => { var cc = m.GlobalNamespace.GetTypeMember("C"); var mm = cc.GetMember<MethodSymbol>("M"); Assert.True(cc.TypeParameters.Single().GetAttributes().IsEmpty); Assert.Equal("XAttribute", mm.TypeParameters.Single().GetAttributes().Single().ToString()); }); } [WorkItem(1144603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1144603")] [Fact] public void EmitMetadataOnlyInPresenceOfErrors() { var source1 = @" public sealed class DiagnosticAnalyzerAttribute : System.Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public static class LanguageNames { public const xyz CSharp = ""C#""; } "; var compilation1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll); compilation1.VerifyDiagnostics( // (10,18): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // public const xyz CSharp = "C#"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "xyz").WithArguments("xyz").WithLocation(10, 18)); var source2 = @" [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpCompilerDiagnosticAnalyzer {} "; var compilation2 = CreateCompilationWithMscorlib40(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll, assemblyName: "Test.dll"); Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols[1]); compilation2.VerifyDiagnostics(); var emitResult2 = compilation2.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult2.Success); emitResult2.Diagnostics.Verify( // error CS7038: Failed to emit module 'Test.dll': Module has invalid attributes. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("Test.dll", "Module has invalid attributes.").WithLocation(1, 1)); // Use different mscorlib to test retargeting scenario var compilation3 = CreateCompilationWithMscorlib45(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll); Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols[1]); compilation3.VerifyDiagnostics( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); var emitResult3 = compilation3.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult3.Success); emitResult3.Diagnostics.Verify( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); } [Fact, WorkItem(30833, "https://github.com/dotnet/roslyn/issues/30833")] public void AttributeWithTaskDelegateParameter() { string code = @" using System; using System.Threading.Tasks; namespace a { class Class1 { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class CommandAttribute : Attribute { public delegate Task FxCommand(); public CommandAttribute(FxCommand Fx) { this.Fx = Fx; } public FxCommand Fx { get; set; } } [Command(UserInfo)] public static async Task UserInfo() { await Task.CompletedTask; } } } "; CreateCompilationWithMscorlib46(code).VerifyDiagnostics( // (22,4): error CS0181: Attribute constructor parameter 'Fx' has type 'Class1.CommandAttribute.FxCommand', which is not a valid attribute parameter type // [Command(UserInfo)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Command").WithArguments("Fx", "a.Class1.CommandAttribute.FxCommand").WithLocation(22, 4)); } [Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/issues/33388")] public void AttributeCrashRepro_33388() { string source = @" using System; public static class C { public static int M(object obj) => 42; public static int M(C2 c2) => 42; } public class RecAttribute : Attribute { public RecAttribute(int i) { this.i = i; } private int i; } [Rec(C.M(null))] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Rec(C.M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(null)").WithLocation(20, 6)); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttribute_Delegate() { string source = @" using System; public class C { [Obsolete] public void M() { } void M2() { Action a = M; a = new Action(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS0612: 'C.M()' is obsolete // Action a = M; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(12, 20), // (13,24): warning CS0612: 'C.M()' is obsolete // a = new Action(M); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(13, 24) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttributeWithUnsafeError() { string source = @" using System; unsafe delegate byte* D(); class C { [Obsolete(null, true)] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (7,35): warning CS0612: 'C.F()' is obsolete // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "F").WithArguments("C.F()").WithLocation(7, 35), // (8,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(8, 28) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void UnmanagedAttributeWithUnsafeError() { string source = @" using System.Runtime.InteropServices; unsafe delegate byte* D(); class C { [UnmanagedCallersOnly] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class UnmanagedCallersOnlyAttribute : Attribute { public UnmanagedCallersOnlyAttribute() { } public Type[] CallConvs; public string EntryPoint; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (8,35): error CS8902: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("C.F()").WithLocation(8, 35), // (9,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(9, 28) ); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage() { var lib_cs = @" public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_2() { var source = @" class A<T> : System.Attribute {} class A : System.Attribute {} [A] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 14) ); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_3() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_4() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_5() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void MetadataForUsingGenericAttribute() { var source = @" public class A<T> : System.Attribute {} public class C { [A<int>] public void M() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); static void validate(ModuleSymbol module) { var m = (MethodSymbol)module.ContainingAssembly.GlobalNamespace.GetMember("C.M"); var attribute = m.GetAttributes().Single(); Assert.Equal("A<System.Int32>", attribute.AttributeClass.ToTestDisplayString()); Assert.Equal("A<System.Int32>..ctor()", attribute.AttributeConstructor.ToTestDisplayString()); } } [Fact] public void AmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [A<int>] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2)); } [Fact, WorkItem(54772, "https://github.com/dotnet/roslyn/issues/54772")] public void ResolveAmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [@A<int>] [AAttribute<int>] public class C { }"; // This behavior is incorrect. No ambiguity errors should be reported in the above program. var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [@A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "@A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [AAttribute<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "AAttribute<int>").WithArguments("generic attributes").WithLocation(6, 2)); } [Fact] public void InheritGenericAttribute() { var source1 = @" public class C<T> : System.Attribute { } public class D : C<int> { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void InheritGenericAttributeInMetadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D extends class C`1<int32> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class C`1<int32>::.ctor() ret } } "; var source = @" [D] public class Program { } "; // Note that this behavior predates the "generic attributes" feature in C# 10. // If a type deriving from a generic attribute is found in metadata, it's permitted to be used as an attribute in C# 9 and below. var comp = CreateCompilationWithIL(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); comp = CreateCompilationWithIL(source, il); comp.VerifyDiagnostics(); } [Fact] public void InheritAttribute_BaseInsideGeneric() { var source1 = @" public class C<T> { public class Inner : System.Attribute { } } public class D : C<int>.Inner { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,26): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class Inner : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(4, 26)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void GenericAttribute_Constraints() { var source = @" public class C<T> : System.Attribute where T : struct { } [C<object>] // 1 public class C1 { } [C<int>] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C<T>' // [C<object>] // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "object").WithArguments("C<T>", "T", "object").WithLocation(4, 4)); } [Fact] public void GenericAttribute_ErrorTypeArg() { var source = @" public class C<T> : System.Attribute { } [C<ERROR>] [C<System>] [C<>] public class Program { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<ERROR>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<ERROR>").WithArguments("generic attributes").WithLocation(4, 2), // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<System>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<System>").WithArguments("generic attributes").WithLocation(5, 2), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_Reflection_CoreClr() { var source = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class Program { public static void Main() { var attr = Attribute.GetCustomAttribute(typeof(Program), typeof(Attr<int>)); Console.Write(attr); } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_False() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] // 1 [Attr<int>] // 2 public class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<object>] // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<object>").WithArguments("Attr<>").WithLocation(8, 2), // (9,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<int>] // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<int>").WithArguments("Attr<>").WithLocation(9, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_True() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] [Attr<int>] public class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32] Attr`1[System.Object] Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeInvalidMultipleFromMetadata() { // This IL includes an attribute with `AllowMultiple = false` (the default). // Then the class `D` includes two copies of the attribute. var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { // [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 ff 7f 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D { .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using System; class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(D)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var comp = CreateCompilationWithIL(source, il, options: TestOptions.DebugExe); var verifier = CompileAndVerify( comp, expectedOutput: "C`1[System.Int32] C`1[System.Int32]"); verifier.VerifyDiagnostics(); } [Fact] [WorkItem(54778, "https://github.com/dotnet/roslyn/issues/54778")] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void GenericAttribute_AttributeDependentTypes() { var source = @" #nullable enable using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr<T> : Attribute { } [Attr<dynamic>] // 1 [Attr<List<dynamic>>] // 2 [Attr<nint>] // 3 [Attr<List<nint>>] // 4 [Attr<string?>] // 5 [Attr<List<string?>>] // 6 [Attr<(int a, int b)>] // 7 [Attr<List<(int a, int b)>>] // 8 [Attr<(int a, string? b)>] // 9 [Attr<ValueTuple<int, int>>] // ok class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS8960: Type 'dynamic' cannot be used in this context because it cannot be represented in metadata. // [Attr<dynamic>] // 1 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<dynamic>").WithArguments("dynamic").WithLocation(10, 2), // (11,2): error CS8960: Type 'List<dynamic>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<dynamic>>] // 2 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<dynamic>>").WithArguments("List<dynamic>").WithLocation(11, 2), // (12,2): error CS8960: Type 'nint' cannot be used in this context because it cannot be represented in metadata. // [Attr<nint>] // 3 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<nint>").WithArguments("nint").WithLocation(12, 2), // (13,2): error CS8960: Type 'List<nint>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<nint>>] // 4 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<nint>>").WithArguments("List<nint>").WithLocation(13, 2), // (14,2): error CS8960: Type 'string?' cannot be used in this context because it cannot be represented in metadata. // [Attr<string?>] // 5 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<string?>").WithArguments("string?").WithLocation(14, 2), // (15,2): error CS8960: Type 'List<string?>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<string?>>] // 6 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<string?>>").WithArguments("List<string?>").WithLocation(15, 2), // (16,2): error CS8960: Type '(int a, int b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, int b)>] // 7 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, int b)>").WithArguments("(int a, int b)").WithLocation(16, 2), // (17,2): error CS8960: Type 'List<(int a, int b)>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<(int a, int b)>>] // 8 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<(int a, int b)>>").WithArguments("List<(int a, int b)>").WithLocation(17, 2), // (18,2): error CS8960: Type '(int a, string? b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, string? b)>] // 9 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, string? b)>").WithArguments("(int a, string? b)").WithLocation(18, 2)); } [Fact] public void GenericAttributeRestrictedTypeArgument() { var source = @" using System; class Attr<T> : Attribute { } [Attr<int*>] // 1 class C1 { } [Attr<delegate*<int, void>>] // 2 class C2 { } [Attr<TypedReference>] // 3 class C3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,7): error CS0306: The type 'int*' may not be used as a type argument // [Attr<int*>] // 1 Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(5, 7), // (8,7): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument // [Attr<delegate*<int, void>>] // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>").WithArguments("delegate*<int, void>").WithLocation(8, 7), // (11,7): error CS0306: The type 'TypedReference' may not be used as a type argument // [Attr<TypedReference>] // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(11, 7)); } [Fact] public void GenericAttribute_AbstractStatic_01() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2Base : Attribute { public virtual void M() { } } class Attr2<T> : Attr2Base where T : I1 { public override void M() { T.M(); } } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { Console.Write(""C.M""); } } [Attr1<C>] [Attr2<C>] class C1 { public static void Main() { var attr2 = (Attr2Base)Attribute.GetCustomAttribute(typeof(C), typeof(Attr2Base)); attr2.M(); } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.Net60); comp.VerifyEmitDiagnostics(); } [Fact] public void GenericAttributeOnLambda() { var source = @" using System; class Attr<T> : Attribute { } class C { void M() { Func<string, string> x = [Attr<int>] (string x) => x; x(""a""); } } "; var verifier = CompileAndVerify(source, symbolValidator: validateMetadata, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifier.VerifyDiagnostics(); void validateMetadata(ModuleSymbol module) { var lambda = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c.<M>b__0_0"); var attrs = lambda.GetAttributes(); Assert.Equal(new[] { "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeSimilarToWellKnownAttribute() { var source = @" using System; class ObsoleteAttribute<T> : Attribute { } class C { [Obsolete<int>] void M0() { } void M1() => M0(); [Obsolete] void M2() { } void M3() => M2(); // 1 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS0612: 'C.M2()' is obsolete // void M3() => M2(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M2()").WithArguments("C.M2()").WithLocation(15, 18)); } [Fact] public void GenericAttributesConsumeFromVB() { var csSource = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class C { } "; var comp = CreateCompilation(csSource); var vbSource = @" Public Class D Inherits C End Class "; var comp2 = CreateVisualBasicCompilation(vbSource, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(comp.EmitToImageReference())); var d = comp2.GetMember<INamedTypeSymbol>("D"); var attrs = d.BaseType.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Attr(Of System.Int32)", attrs[0].AttributeClass.ToTestDisplayString()); } [Fact] public void GenericAttribute_AbstractStatic_02() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2<T> : Attribute where T : I1 { } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { } } [Attr1<I1>] [Attr2<I1>] class C1 { } [Attr1<I2>] [Attr2<I2>] class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static abstract void M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M").WithLocation(8, 26), // (13,11): error CS8929: 'C.M()' cannot implement interface member 'I1.M()' in type 'C' because the target runtime doesn't support static abstract members in interfaces. // class C : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("C.M()", "I1.M()", "C").WithLocation(13, 11), // (19,8): error CS8920: The interface 'I1' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I1>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I1").WithArguments("Attr2<T>", "I1", "T", "I1").WithLocation(19, 8), // (23,8): error CS8920: The interface 'I2' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I2>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I2").WithArguments("Attr2<T>", "I1", "T", "I2").WithLocation(23, 8)); } [Fact] public void GenericAttributeProperty_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public T Prop { get; set; } } [Attr<string>(Prop = ""a"")] class Program { static void Main() { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { foreach (var arg in attr.NamedArguments) { Console.Write(arg.MemberName); Console.Write("" = ""); Console.Write(arg.TypedValue.Value); } } } } "; var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verify, expectedOutput: "Prop = a"); void verify(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<TypeSymbol>("Program"); var attrs = program.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(Prop = \"a\")" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeProperty_02() { var source = @" using System; class Attr<T1> : Attribute { public object Prop { get; set; } } class Outer<T2> { [Attr<object>(Prop = default(T2))] // 1 class Program1 { } [Attr<T2>(Prop = default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(Prop = default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 26), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,22): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 22)); } [ConditionalFact(typeof(CoreClrOnly)), WorkItem(55190, "https://github.com/dotnet/roslyn/issues/55190")] public void GenericAttributeParameter_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public Attr(T param) { } } [Attr<string>(""a"")] class Holder { } class Program { static void Main() { try { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Holder)); foreach (var attr in attrs) { foreach (var arg in attr.ConstructorArguments) { Console.Write(arg.Value); } } } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; // The expected output here will change once we consume a runtime // which has a fix for https://github.com/dotnet/runtime/issues/56492 var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verifyMetadata, expectedOutput: "CustomAttributeFormatException"); verifier.VerifyTypeIL("Holder", @" .class private auto ansi beforefieldinit Holder extends [netstandard]System.Object { .custom instance void class Attr`1<string>::.ctor(!0) = ( 01 00 01 61 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Holder::.ctor } // end of class Holder "); void verify(ModuleSymbol module) { var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(\"a\")" }, GetAttributeStrings(attrs)); } void verifyMetadata(ModuleSymbol module) { // https://github.com/dotnet/roslyn/issues/55190 // The compiler should be able to read this attribute argument from metadata. // Once this is fixed, we should be able to use exactly the same 'verify' method for both source and metadata. var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeParameter_02() { var source = @" using System; class Attr<T> : Attribute { public Attr(object param) { } } class Outer<T2> { [Attr<object>(default(T2))] // 1 class Program1 { } [Attr<T2>(default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 19), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 15)); } [Fact] public void GenericAttributeOnAssembly() { var source = @" using System; [assembly: Attr<string>] [assembly: Attr<int>] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verifySource); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)", "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } void verifySource(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeReflection_OpenGeneric() { var source = @" using System; class Attr<T> : Attribute { } class Attr2<T> : Attribute { } [Attr<string>] [Attr2<int>] class Holder { } class Program { static void Main() { try { var attr = Attribute.GetCustomAttribute(typeof(Holder), typeof(Attr<>)); Console.Write(attr?.ToString() ?? ""not found""); } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "not found"); verifier.VerifyDiagnostics(); } [Fact] public void GenericAttributeNested() { var source = @" using System; class Attr<T> : Attribute { } [Attr<Attr<string>>] class C { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verify); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attrs = c.GetAttributes(); Assert.Equal(new[] { "Attr<Attr<System.String>>" }, GetAttributeStrings(attrs)); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests : WellKnownAttributesTestBase { static readonly string[] s_autoPropAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }; static readonly string[] s_backingFieldAttributes = new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; #region Function Tests [Fact, WorkItem(26464, "https://github.com/dotnet/roslyn/issues/26464")] public void TestNullInAssemblyVersionAttribute() { var source = @" [assembly: System.Reflection.AssemblyVersionAttribute(null)] class Program { }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (2,55): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersionAttribute(null)] Diagnostic(ErrorCode.ERR_InvalidVersionFormat, "null").WithLocation(2, 55) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void TestQuickAttributeChecker() { var predefined = QuickAttributeChecker.Predefined; var typeForwardedTo = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeForwardedTo")); var typeIdentifier = SyntaxFactory.Attribute(SyntaxFactory.ParseName("TypeIdentifier")); Assert.True(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeForwardedTo)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeForwardedTo, QuickAttributes.None)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeForwardedTo)); Assert.True(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.TypeIdentifier)); Assert.False(predefined.IsPossibleMatch(typeIdentifier, QuickAttributes.None)); var alias1 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias1")); var checker1 = WithAliases(predefined, "using alias1 = TypeForwardedToAttribute;"); Assert.True(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1a = WithAliases(checker1, "using alias1 = TypeIdentifierAttribute;"); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.True(checker1a.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); var checker1b = WithAliases(checker1, "using alias2 = TypeIdentifierAttribute;"); var alias2 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias2")); Assert.True(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeForwardedTo)); Assert.False(checker1b.IsPossibleMatch(alias1, QuickAttributes.TypeIdentifier)); Assert.False(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeForwardedTo)); Assert.True(checker1b.IsPossibleMatch(alias2, QuickAttributes.TypeIdentifier)); var checker3 = WithAliases(predefined, "using alias3 = TypeForwardedToAttribute; using alias3 = TypeIdentifierAttribute;"); var alias3 = SyntaxFactory.Attribute(SyntaxFactory.ParseName("alias3")); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeForwardedTo)); Assert.True(checker3.IsPossibleMatch(alias3, QuickAttributes.TypeIdentifier)); QuickAttributeChecker WithAliases(QuickAttributeChecker checker, string aliases) { var nodes = Parse(aliases).GetRoot().DescendantNodes().OfType<UsingDirectiveSyntax>(); var list = new SyntaxList<UsingDirectiveSyntax>().AddRange(nodes); return checker.AddAliasesIfAny(list); } } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant // but C won't exist "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithDiagnostic() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (3,60): error CS1503: Argument 1: cannot convert from 'int' to 'System.Type' // [assembly: System.Runtime.CompilerServices.TypeForwardedTo(1)] Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "System.Type").WithLocation(3, 60) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithMissingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' // but C won't exist "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics( // (2,12): error CS7068: Reference to type 'C' claims it is defined in this assembly, but it is not defined in source or any added modules // [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' Diagnostic(ErrorCode.ERR_MissingTypeInSource, "RefersToLib").WithArguments("C").WithLocation(2, 12) ); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithStaticUsing() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using static RefersToLibAttribute; // Binding this will cause a lookup for 'C' in 'lib'. // Such lookup requires binding 'TypeForwardedTo' attributes (and aliases), but we should not bind other usings, to avoid an infinite recursion. [assembly: System.Reflection.AssemblyTitleAttribute(""title"")] public class Ignore { public void UseStaticUsing() { Method(); } } "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } public static void Method() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] // but C is forwarded "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); var newLibComp3 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp3.SourceAssembly.GetAttributes(); newLibComp3.VerifyDiagnostics(); } /// <summary> /// Looking up C explicitly after calling GetAttributes will cause <see cref="SourceAssemblySymbol.GetForwardedTypes"/> to use the cached attributes, rather that do partial binding /// </summary> [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithCheckAttributes() { var cDefinition_cs = @"public class C { }"; var derivedDefinition_cs = @"public class Derived : C { }"; var typeForward_cs = @" [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(C))] "; var origLibComp = CreateCompilation(cDefinition_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var compWithDerivedAndReferenceToLib = CreateCompilation(typeForward_cs + derivedDefinition_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithDerivedAndReferenceToLib.VerifyDiagnostics(); var compWithC = CreateCompilation(cDefinition_cs, assemblyName: "new"); compWithC.VerifyDiagnostics(); var newLibComp = CreateCompilation(typeForward_cs, references: new[] { compWithDerivedAndReferenceToLib.EmitToImageReference(), compWithC.EmitToImageReference() }, assemblyName: "lib"); var attribute = newLibComp.SourceAssembly.GetAttributes().Single(); // GetAttributes binds all attributes Assert.Equal("System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(C))", attribute.ToString()); var derived = (NamedTypeSymbol)newLibComp.GetMember("Derived"); var c = derived.BaseType(); // get C Assert.Equal("C", c.ToTestDisplayString()); Assert.False(c.IsErrorType()); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithTypeForward_WithRelevantType_WithAlias() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" using alias1 = System.Runtime.CompilerServices.TypeForwardedToAttribute; [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' [assembly: alias1(typeof(C))] // but C is forwarded via alias "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithIrrelevantType() { var origLib_cs = @"public class C { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll want to lookup type C in 'lib' (during overload resolution of attribute constructors) albeit irrelevant public class C { } // and C exists here "; var reference_cs = @"using System; public class RefersToLibAttribute : Attribute { public RefersToLibAttribute() { } public RefersToLibAttribute(C c) { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] [WorkItem(21194, "https://github.com/dotnet/roslyn/issues/21194")] public void AttributeWithTypeReferenceToCurrentCompilation_WithExistingType_WithRelevantType() { var origLib_cs = @"public class C : System.Attribute { }"; var newLib_cs = @" [assembly: RefersToLib] // to bind this, we'll need to find type C in 'lib' public class C : System.Attribute { } // and C exists here "; var reference_cs = @" public class RefersToLibAttribute : C { public RefersToLibAttribute() { } } "; var origLibComp = CreateCompilation(origLib_cs, assemblyName: "lib"); origLibComp.VerifyDiagnostics(); var newComp = CreateCompilation(origLib_cs, assemblyName: "new"); newComp.VerifyDiagnostics(); var compWithReferenceToLib = CreateCompilation(reference_cs, references: new[] { origLibComp.EmitToImageReference() }); compWithReferenceToLib.VerifyDiagnostics(); var newLibComp = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.EmitToImageReference(), newComp.EmitToImageReference() }, assemblyName: "lib"); newLibComp.VerifyDiagnostics(); var newLibComp2 = CreateCompilation(newLib_cs, references: new[] { compWithReferenceToLib.ToMetadataReference(), newComp.ToMetadataReference() }, assemblyName: "lib"); newLibComp2.VerifyDiagnostics(); } [Fact] public void TestAssemblyAttributes() { var source = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Roslyn.Compilers.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.UnitTests"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.CSharp.Test.Utilities"")] [assembly: InternalsVisibleTo(""Roslyn.Compilers.VisualBasic"")] class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { Symbol assembly = m.ContainingSymbol; var attrs = assembly.GetAttributes(); Assert.Equal(5, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.UnitTests"")", attrs[0].ToString()); attrs[1].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp"")", attrs[1].ToString()); attrs[2].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.UnitTests"")", attrs[2].ToString()); attrs[3].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.CSharp.Test.Utilities"")", attrs[3].ToString()); attrs[4].VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic"); Assert.Equal(@"System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Roslyn.Compilers.VisualBasic"")", attrs[4].ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnStringParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { } } [Mark(b: new string[] { ""Hello"", ""World"" }, a: true)] [Mark(b: ""Hello"", true)] static class Program { }", parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (11,2): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Mark(b: new string[] { "Hello", "World" }, a: true)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"Mark(b: new string[] { ""Hello"", ""World"" }, a: true)").WithLocation(11, 2), // (12,7): error CS8323: Named argument 'b' is used out-of-position but is followed by an unnamed argument // [Mark(b: "Hello", true)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "b").WithArguments("b").WithLocation(12, 7) ); } [Fact] public void TestNullAsParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; class MarkAttribute : Attribute { public MarkAttribute(params object[] b) { } } [Mark(null)] static class Program { }"); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnOrderedObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, b: new object[] { ""Hello"", ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: new object[] { ""Hello"", ""World"" }, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""B.Length={attr.B.Length}, B[0]={attr.B[0]}, B[1]={attr.B[1]}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"B.Length=2, B[0]=Hello, B[1]=World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument2() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { A = a; B = b; } public bool A { get; } public object[] B { get; } } [Mark(b: ""Hello"", a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B.Length={attr.B.Length}, B[0]={attr.B[0]}""); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"A=True, B.Length=1, B[0]=Hello"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument3() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument4() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(a: true, new object[] { ""Hello"" }, new object[] { ""World"" })] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); var worldArray = (object[])attr.B[1]; Console.Write(worldArray[0]); } }", options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"World"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 0, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnObjectParamsArgument5() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(bool a, params object[] b) { B = b; } public object[] B { get; } } [Mark(b: null, a: true)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write(attr.B == null); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: @"True"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, -1 }, attributeData.ConstructorArgumentsSourceIndices); } [Fact] [WorkItem(20741, "https://github.com/dotnet/roslyn/issues/20741")] public void TestNamedArgumentOnNonParamsArgument() { var comp = CreateCompilationWithMscorlib46(@" using System; using System.Reflection; sealed class MarkAttribute : Attribute { public MarkAttribute(int a, int b) { A = a; B = b; } public int A { get; } public int B { get; } } [Mark(b: 42, a: 1)] static class Program { public static void Main() { var attr = typeof(Program).GetCustomAttribute<MarkAttribute>(); Console.Write($""A={attr.A}, B={attr.B}""); } }", options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "A=1, B=42"); var program = (NamedTypeSymbol)comp.GetMember("Program"); var attributeData = (SourceAttributeData)program.GetAttributes()[0]; Assert.Equal(new[] { 1, 0 }, attributeData.ConstructorArgumentsSourceIndices); } [WorkItem(984896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984896")] [Fact] public void TestAssemblyAttributesErr() { string code = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using M = System.Math; namespace My { using A.B; // TODO: <Insert justification for suppressing TestId> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Test"",""TestId"",Justification=""<Pending>"")] public unsafe partial class A : C, I { } } "; var source = CreateCompilationWithMscorlib40AndSystemCore(code); // the following should not crash source.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, source.SyntaxTrees[0], filterSpanWithinTree: null, includeEarlierStages: true); } [Fact, WorkItem(545326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545326")] public void TestAssemblyAttributes_Bug13670() { var source = @" using System; [assembly: A(Derived.Str)] public class A: Attribute { public A(string x){} public static void Main() {} } public class Derived: Base { internal const string Str = ""temp""; public override int Goo { get { return 1; } } } public class Base { public virtual int Goo { get { return 0; } } } "; CompileAndVerify(source); } [Fact] public void TestAssemblyAttributesReflection() { var compilation = CreateCompilation(@" using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // These are not pseudo attributes, but encoded as bits in metadata [assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] [assembly: AssemblyCultureAttribute("""")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] [assembly: AssemblyVersion(""1.2.*"")] [assembly: AssemblyFileVersionAttribute(""4.3.2.100"")] class C { public static void Main() {} } "); var attrs = compilation.Assembly.GetAttributes(); Assert.Equal(8, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyAlgorithmIdAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5); Assert.Equal(@"System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)", a.ToString()); break; case "AssemblyCultureAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, ""); Assert.Equal(@"System.Reflection.AssemblyCultureAttribute("""")", a.ToString()); break; case "AssemblyDelaySignAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal(@"System.Reflection.AssemblyDelaySignAttribute(true)", a.ToString()); break; case "AssemblyFlagsAttribute": a.VerifyValue(0, TypedConstantKind.Enum, (int)AssemblyNameFlags.Retargetable); Assert.Equal(@"System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.Retargetable)", a.ToString()); break; case "AssemblyKeyFileAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "MyKey.snk"); Assert.Equal(@"System.Reflection.AssemblyKeyFileAttribute(""MyKey.snk"")", a.ToString()); break; case "AssemblyKeyNameAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "Key Name"); Assert.Equal(@"System.Reflection.AssemblyKeyNameAttribute(""Key Name"")", a.ToString()); break; case "AssemblyVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "1.2.*"); Assert.Equal(@"System.Reflection.AssemblyVersionAttribute(""1.2.*"")", a.ToString()); break; case "AssemblyFileVersionAttribute": a.VerifyValue(0, TypedConstantKind.Primitive, "4.3.2.100"); Assert.Equal(@"System.Reflection.AssemblyFileVersionAttribute(""4.3.2.100"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } // Verify that resolving an attribute defined within a class on a class does not cause infinite recursion [Fact] public void TestAttributesOnClassDefinedInClass() { var compilation = CreateCompilation(@" using System; using System.Runtime.CompilerServices; [A.X()] public class A { [AttributeUsage(AttributeTargets.All, allowMultiple = true)] public class XAttribute : Attribute { } } class C { public static void Main() {} } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("A.XAttribute", attrs.First().AttributeClass.ToDisplayString()); } [Fact] public void TestAttributesOnClassWithConstantDefinedInClass() { var compilation = CreateCompilation(@" using System; [Attr(Goo.p)] class Goo { private const object p = null; } internal class AttrAttribute : Attribute { public AttrAttribute(object p) { } } class C { public static void Main() { } } "); var attrs = compilation.SourceModule.GlobalNamespace.GetMember("Goo").GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue<object>(0, TypedConstantKind.Primitive, null); } [Fact] public void TestAttributeEmit() { var compilation = CreateCompilation(@" using System; public enum e1 { a, b, c } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute(int i) { } public XAttribute(int i, string s) { } public XAttribute(int i, string s, e1 e) { } public XAttribute(object[] o) { } public XAttribute(int[] i) { } public XAttribute(int[] i, string[] s) { } public XAttribute(int[] i, string[] s, e1[] e) { } public int pi { get; set; } public string ps { get; set; } public e1 pe { get; set; } } [X(1, ""hello"", e1.a)] [X(new int[] { 1 }, new string[] { ""hello"" }, new e1[] { e1.a, e1.b, e1.c })] [X(new object[] { 1, ""hello"", e1.a })] class C { public static void Main() {} } "); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("XAttribute..ctor(int)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Attribute..ctor()"" IL_0006: ret }"); } [Fact] public void TestAttributesOnClassProperty() { var compilation = CreateCompilation(@" using System; public class A { [CLSCompliant(true)] public string Prop { get { return null; } } } class C { public static void Main() {} } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var prop = type.GetMember("Prop"); var attrs = prop.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, true); Assert.Equal("System.CLSCompliantAttribute", attrs.First().AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688268")] [Fact] public void Bug688268() { var compilation = CreateCompilation(@" using System; using System.Runtime.InteropServices; using System.Security; public interface I { void _VtblGap1_30(); void _VtblGaP1_30(); } "); System.Action<ModuleSymbol> metadataValidator = delegate (ModuleSymbol module) { var metadata = ((PEModuleSymbol)module).Module; var typeI = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMembers("I").Single(); var methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle); Assert.Equal(2, methods.Count); var e = methods.GetEnumerator(); e.MoveNext(); var flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, flags); e.MoveNext(); flags = metadata.GetMethodDefFlagsOrThrow(e.Current); Assert.Equal( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract, flags); }; CompileAndVerify( compilation, sourceSymbolValidator: null, symbolValidator: metadataValidator); } [Fact] public void TestAttributesOnPropertyAndGetSet() { string source = @" using System; [AObject(typeof(object), O = A.obj)] public class A { internal const object obj = null; public string RProp { [AObject(new object[] { typeof(string) })] get { return null; } } [AObject(new object[] { 1, ""two"", typeof(string), 3.1415926 })] public object WProp { [AObject(new object[] { new object[] { typeof(string) } })] set { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var type = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal("AObjectAttribute(typeof(object), O = null)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeof(object)); attrs.First().VerifyNamedArgumentValue<object>(0, "O", TypedConstantKind.Primitive, null); var prop = type.GetMember<PropertySymbol>("RProp"); attrs = prop.GetMethod.GetAttributes(); Assert.Equal("AObjectAttribute({typeof(string)})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { typeof(string) }); prop = type.GetMember<PropertySymbol>("WProp"); attrs = prop.GetAttributes(); Assert.Equal(@"AObjectAttribute({1, ""two"", typeof(string), 3.1415926})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { 1, "two", typeof(string), 3.1415926 }); attrs = prop.SetMethod.GetAttributes(); Assert.Equal(@"AObjectAttribute({{typeof(string)}})", attrs.First().ToString()); attrs.First().VerifyValue(0, TypedConstantKind.Array, new object[] { new object[] { typeof(string) } }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestFieldAttributeOnPropertyInCSharp7_2() { string source = @" public class A : System.Attribute { } public class Test { [field: System.Obsolete] [field: A] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_2); comp.VerifyDiagnostics( // (7,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(7, 6), // (8,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: A] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(8, 6), // (11,6): warning CS8361: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. // [field: System.Obsolete("obsolete", error: true)] Diagnostic(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable, "field:").WithArguments("7.2", "7.3").WithLocation(11, 6) ); } [Fact] public void TestFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { public A(int i) { } } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { public B(int i) { } } public class Test { [field: A(1)] public int P { get; set; } [field: A(2)] public int P2 { get; } [B(3)] [field: A(33)] public int P3 { get; } [property: B(4)] [field: A(44)] [field: A(444)] public int P4 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); Assert.Null(prop2.SetMethod); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(2)" }), GetAttributeStrings(field2.GetAttributes())); var prop3 = @class.GetMember<PropertySymbol>("P3"); Assert.Equal("B(3)", prop3.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop3.SetMethod); var field3 = @class.GetMember<FieldSymbol>("<P3>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(33)" }), GetAttributeStrings(field3.GetAttributes())); var prop4 = @class.GetMember<PropertySymbol>("P4"); Assert.Equal("B(4)", prop4.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop3.GetMethod.GetAttributes())); Assert.Null(prop4.SetMethod); var field4 = @class.GetMember<FieldSymbol>("<P4>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(44)", "A(444)" }), GetAttributeStrings(field4.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestGeneratedTupleAndDynamicAttributesOnAutoProperty() { string source = @" public class Test { public (dynamic a, int b) P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { Assert.Empty(field1.GetAttributes()); } else { var dynamicAndTupleNames = new[] { "System.Runtime.CompilerServices.DynamicAttribute({false, true, false})", @"System.Runtime.CompilerServices.TupleElementNamesAttribute({""a"", ""b""})" }; AssertEx.SetEqual(s_backingFieldAttributes.Concat(dynamicAndTupleNames), GetAttributeStrings(field1.GetAttributes())); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_SpecialName() { string source = @" public struct Test { [field: System.Runtime.CompilerServices.SpecialName] public static int P { get; set; } public static int P2 { get; set; } [field: System.Runtime.CompilerServices.SpecialName] public static int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.HasSpecialName); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.HasSpecialName); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.Runtime.CompilerServices.SpecialNameAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_NonSerialized() { string source = @" public class Test { [field: System.NonSerialized] public int P { get; set; } public int P2 { get; set; } [field: System.NonSerialized] public int f; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); var attributes1 = field1.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes1)); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(attributes1)); } Assert.True(field1.IsNotSerialized); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); Assert.False(field2.IsNotSerialized); var field3 = @class.GetMember<FieldSymbol>("f"); var attributes3 = field3.GetAttributes(); if (isFromSource) { AssertEx.SetEqual(new[] { "System.NonSerializedAttribute" }, GetAttributeStrings(attributes3)); } else { Assert.Empty(GetAttributeStrings(attributes3)); } Assert.True(field3.IsNotSerialized); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(0)] public static int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS0637: The FieldOffset attribute is not allowed on static or const fields // [field: System.Runtime.InteropServices.FieldOffset(0)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadField, "System.Runtime.InteropServices.FieldOffset").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset2() { string source = @" public struct Test { [field: System.Runtime.InteropServices.FieldOffset(-1)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0591: Invalid value for argument to 'System.Runtime.InteropServices.FieldOffset' attribute // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "-1").WithArguments("System.Runtime.InteropServices.FieldOffset").WithLocation(4, 56), // (4,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: System.Runtime.InteropServices.FieldOffset(-1)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "System.Runtime.InteropServices.FieldOffset").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset3() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Auto)] public class Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(7, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset4() { string source = @" using System.Runtime.InteropServices; public struct Test { [field: FieldOffset(4)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) // [field: FieldOffset(4)] Diagnostic(ErrorCode.ERR_StructOffsetOnBadStruct, "FieldOffset").WithLocation(6, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_FieldOffset5() { string source = @" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct Test { public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,16): error CS0625: 'Test.P': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int P { get; set; } Diagnostic(ErrorCode.ERR_MissingStructOffset, "P").WithArguments("Test.P").WithLocation(7, 16) ); } [Fact] public void TestWellKnownAttributeOnProperty_FixedBuffer() { string source = @" public class Test { [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS8362: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property // [field: System.Runtime.CompilerServices.FixedBuffer(typeof(int), 0)] Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttrOnProperty, "System.Runtime.CompilerServices.FixedBuffer").WithLocation(4, 13) ); } [ConditionalFact(typeof(DesktopOnly))] public void TestWellKnownAttributeOnProperty_DynamicAttribute() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DynamicAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,13): error CS1970: Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead. // [field: System.Runtime.CompilerServices.DynamicAttribute()] Diagnostic(ErrorCode.ERR_ExplicitDynamicAttr, "System.Runtime.CompilerServices.DynamicAttribute()").WithLocation(4, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsReadOnlyAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsReadOnlyAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsReadOnlyAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsReadOnlyAttribute()").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_IsByRefLikeAttribute() { string source = @" namespace System.Runtime.CompilerServices { public class IsByRefLikeAttribute : System.Attribute { } } public class Test { [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage. // [field: System.Runtime.CompilerServices.IsByRefLikeAttribute()] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "System.Runtime.CompilerServices.IsByRefLikeAttribute()").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(8, 13) ); } [Fact] public void TestWellKnownAttributeOnProperty_DateTimeConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public System.DateTime P { get; set; } [field: System.Runtime.CompilerServices.DateTimeConstant(123456)] public int P2 { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field1.GetAttributes())); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.Runtime.CompilerServices.DateTimeConstantAttribute(123456)" }), GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_DecimalConstant() { string source = @" public class Test { [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal P { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public int P2 { get; set; } [field: System.Runtime.CompilerServices.DecimalConstant(0, 0, 100, 100, 100)] public decimal field; } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var fieldAttributesExpected = isFromSource ? new string[0] : new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute", "System.Diagnostics.DebuggerBrowsableAttribute(System.Diagnostics.DebuggerBrowsableState.Never)" }; var constantExpected = "1844674407800451891300"; string[] decimalAttributeExpected = new[] { "System.Runtime.CompilerServices.DecimalConstantAttribute(0, 0, 100, 100, 100)" }; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); if (isFromSource) { AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field1.GetAttributes())); } else { AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field1.GetAttributes())); Assert.Equal(constantExpected, field1.ConstantValue.ToString()); } var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(decimalAttributeExpected), GetAttributeStrings(field2.GetAttributes())); var field3 = @class.GetMember<FieldSymbol>("field"); if (isFromSource) { AssertEx.SetEqual(decimalAttributeExpected, GetAttributeStrings(field3.GetAttributes())); } else { Assert.Empty(GetAttributeStrings(field3.GetAttributes())); Assert.Equal(constantExpected, field3.ConstantValue.ToString()); } }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestWellKnownAttributeOnProperty_TupleElementNamesAttribute() { string source = @" namespace System.Runtime.CompilerServices { public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } public class Test { [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })] public int P { get; set; } } "; var comp = CreateCompilationWithMscorlib40(source); comp.VerifyDiagnostics( // (11,13): error CS8138: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. // [field: System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { "hello" })] Diagnostic(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, @"System.Runtime.CompilerServices.TupleElementNamesAttribute(new[] { ""hello"" })").WithLocation(11, 13) ); } [Fact] public void TestWellKnownEarlyAttributeOnProperty_Obsolete() { string source = @" public class Test { [field: System.Obsolete] public int P { get; set; } [field: System.Obsolete(""obsolete"", error: true)] public int P2 { get; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); bool isFromSource = @class is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = @class.GetMember<PropertySymbol>("P"); Assert.Empty(prop1.GetAttributes()); var field1 = @class.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "System.ObsoleteAttribute" }), GetAttributeStrings(field1.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field1.ObsoleteAttributeData.Kind); Assert.Null(field1.ObsoleteAttributeData.Message); Assert.False(field1.ObsoleteAttributeData.IsError); var prop2 = @class.GetMember<PropertySymbol>("P2"); Assert.Empty(prop2.GetAttributes()); var field2 = @class.GetMember<FieldSymbol>("<P2>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { @"System.ObsoleteAttribute(""obsolete"", true)" }), GetAttributeStrings(field2.GetAttributes())); Assert.Equal(ObsoleteAttributeKind.Obsolete, field2.ObsoleteAttributeData.Kind); Assert.Equal("obsolete", field2.ObsoleteAttributeData.Message); Assert.True(field2.ObsoleteAttributeData.IsError); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestFieldAttributesOnProperty() { string source = @" public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(9, 6), // (6,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(6, 6) ); } [Fact] public void TestFieldAttributesOnPropertyAccessors() { string source = @" public class A : System.Attribute { } public class Test { public int P { [field: A] get => throw null; set => throw null; } public int P2 { [field: A] get; set; } public int P3 { [field: A] get => throw null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P { [field: A] get => throw null; set => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(6, 21), // (7,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P2 { [field: A] get; set; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(7, 22), // (8,22): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'method, return'. All attributes in this block will be ignored. // public int P3 { [field: A] get => throw null; } Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "method, return").WithLocation(8, 22) ); } [Fact] public void TestMultipleFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false) ] public class Single : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class Multiple : System.Attribute { } public class Test { [field: Single] [field: Single] [field: Multiple] [field: Multiple] public int P { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,13): error CS0579: Duplicate 'Single' attribute // [field: Single] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Single").WithArguments("Single").WithLocation(11, 13) ); } [Fact] public void TestInheritedFieldAttributesOnOverriddenProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, Inherited = true) ] public class A : System.Attribute { public A(int i) { } } public class Base { [field: A(1)] [A(2)] public virtual int P { get; set; } } public class Derived : Base { public override int P { get; set; } } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var parent = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Base"); bool isFromSource = parent is SourceNamedTypeSymbol; var propAttributesExpected = isFromSource ? new string[0] : s_autoPropAttributes; var fieldAttributesExpected = isFromSource ? new string[0] : s_backingFieldAttributes; var prop1 = parent.GetMember<PropertySymbol>("P"); Assert.Equal("A(2)", prop1.GetAttributes().Single().ToString()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop1.SetMethod.GetAttributes())); var field1 = parent.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected.Concat(new[] { "A(1)" }), GetAttributeStrings(field1.GetAttributes())); var child = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var prop2 = child.GetMember<PropertySymbol>("P"); Assert.Empty(prop2.GetAttributes()); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.GetMethod.GetAttributes())); AssertEx.SetEqual(propAttributesExpected, GetAttributeStrings(prop2.SetMethod.GetAttributes())); var field2 = child.GetMember<FieldSymbol>("<P>k__BackingField"); AssertEx.SetEqual(fieldAttributesExpected, GetAttributeStrings(field2.GetAttributes())); }; var comp = CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); } [Fact] public void TestPropertyTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get; set; } [field: A] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(10, 13), // (7,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(7, 13) ); } [Fact] public void TestClassTargetedFieldAttributesOnAutoProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Class) ] public class ClassAllowed : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Field) ] public class FieldAllowed : System.Attribute { } public class Test { [field: ClassAllowed] // error 1 [field: FieldAllowed] public int P { get; set; } [field: ClassAllowed] // error 2 [field: FieldAllowed] public int P2 { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 2 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(14, 13), // (10,13): error CS0592: Attribute 'ClassAllowed' is not valid on this declaration type. It is only valid on 'class' declarations. // [field: ClassAllowed] // error 1 Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "ClassAllowed").WithArguments("ClassAllowed", "class").WithLocation(10, 13) ); } [Fact] public void TestImproperlyTargetedFieldAttributesOnProperty() { string source = @" [System.AttributeUsage(System.AttributeTargets.Property) ] public class A : System.Attribute { } public class Test { [field: A] public int P { get => throw null; set => throw null; } [field: A] public int P2 { get => throw null; } [field: A] public int P3 { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(10, 6), // (13,13): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. // [field: A] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "property, indexer").WithLocation(13, 13), // (7,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'property'. All attributes in this block will be ignored. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "property").WithLocation(7, 6) ); } [Fact] public void TestAttributesOnEvents() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA] //in event decl public event System.Action E1; [event: BB] //in event decl public event System.Action E2; [method: CC] //in both accessors public event System.Action E3; [field: DD] //on field public event System.Action E4; [EE] //in event decl public event System.Action E5 { add { } remove { } } [event: FF] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG] add { } remove { } } //in accessor public event System.Action E8 { [method: HH] add { } remove { } } //in accessor public event System.Action E9 { [param: II] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ] add { } remove { } } //on return (after .param[0]) } "; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromSource => moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var event1 = @class.GetMember<EventSymbol>("E1"); var event2 = @class.GetMember<EventSymbol>("E2"); var event3 = @class.GetMember<EventSymbol>("E3"); var event4 = @class.GetMember<EventSymbol>("E4"); var event5 = @class.GetMember<EventSymbol>("E5"); var event6 = @class.GetMember<EventSymbol>("E6"); var event7 = @class.GetMember<EventSymbol>("E7"); var event8 = @class.GetMember<EventSymbol>("E8"); var event9 = @class.GetMember<EventSymbol>("E9"); var event10 = @class.GetMember<EventSymbol>("E10"); var accessorsExpected = isFromSource ? new string[0] : new[] { "CompilerGeneratedAttribute" }; Assert.Equal("AA", GetSingleAttributeName(event1)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event1.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event1.AssociatedField); Assert.Equal(0, event1.GetFieldAttributes().Length); } Assert.Equal("BB", GetSingleAttributeName(event2)); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event2.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event2.AssociatedField); Assert.Equal(0, event2.GetFieldAttributes().Length); } AssertNoAttributes(event3); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected.Concat(new[] { "CC" }), GetAttributeNames(event3.RemoveMethod.GetAttributes())); if (isFromSource) { AssertNoAttributes(event3.AssociatedField); Assert.Equal(0, event3.GetFieldAttributes().Length); } AssertNoAttributes(event4); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.AddMethod.GetAttributes())); AssertEx.SetEqual(accessorsExpected, GetAttributeNames(event4.RemoveMethod.GetAttributes())); if (isFromSource) { Assert.Equal("DD", GetSingleAttributeName(event4.AssociatedField)); Assert.Equal("DD", event4.GetFieldAttributes().Single().AttributeClass.Name); } Assert.Equal("EE", GetSingleAttributeName(event5)); AssertNoAttributes(event5.AddMethod); AssertNoAttributes(event5.RemoveMethod); Assert.Equal("FF", GetSingleAttributeName(event6)); AssertNoAttributes(event6.AddMethod); AssertNoAttributes(event6.RemoveMethod); AssertNoAttributes(event7); Assert.Equal("GG", GetSingleAttributeName(event7.AddMethod)); AssertNoAttributes(event7.RemoveMethod); AssertNoAttributes(event8); Assert.Equal("HH", GetSingleAttributeName(event8.AddMethod)); AssertNoAttributes(event8.RemoveMethod); AssertNoAttributes(event9); AssertNoAttributes(event9.AddMethod); AssertNoAttributes(event9.RemoveMethod); Assert.Equal("II", GetSingleAttributeName(event9.AddMethod.Parameters.Single())); AssertNoAttributes(event10); AssertNoAttributes(event10.AddMethod); AssertNoAttributes(event10.RemoveMethod); Assert.Equal("JJ", event10.AddMethod.GetReturnTypeAttributes().Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(true), symbolValidator: symbolValidator(false)); } [Fact] public void TestAttributesOnEvents_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class FF : System.Attribute { } public class GG : System.Attribute { } public class HH : System.Attribute { } public class II : System.Attribute { } public class JJ : System.Attribute { } public class Test { [AA(0)] //in event decl public event System.Action E1; [event: BB(0)] //in event decl public event System.Action E2; [method: CC(0)] //in both accessors public event System.Action E3; [field: DD(0)] //on field public event System.Action E4; [EE(0)] //in event decl public event System.Action E5 { add { } remove { } } [event: FF(0)] //in event decl public event System.Action E6 { add { } remove { } } public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) } "; CreateCompilation(source).VerifyDiagnostics( // (15,6): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // [AA(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (17,13): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [event: BB(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (19,14): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [method: CC(0)] //in both accessors Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (21,13): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [field: DD(0)] //on field Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (24,6): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1"), // (26,13): error CS1729: 'FF' does not contain a constructor that takes 1 arguments // [event: FF(0)] //in event decl Diagnostic(ErrorCode.ERR_BadCtorArgCount, "FF(0)").WithArguments("FF", "1"), // (29,38): error CS1729: 'GG' does not contain a constructor that takes 1 arguments // public event System.Action E7 { [GG(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "GG(0)").WithArguments("GG", "1"), // (30,46): error CS1729: 'HH' does not contain a constructor that takes 1 arguments // public event System.Action E8 { [method: HH(0)] add { } remove { } } //in accessor Diagnostic(ErrorCode.ERR_BadCtorArgCount, "HH(0)").WithArguments("HH", "1"), // (31,45): error CS1729: 'II' does not contain a constructor that takes 1 arguments // public event System.Action E9 { [param: II(0)] add { } remove { } } //on parameter (after .param[1]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "II(0)").WithArguments("II", "1"), // (32,47): error CS1729: 'JJ' does not contain a constructor that takes 1 arguments // public event System.Action E10 { [return: JJ(0)] add { } remove { } } //on return (after .param[0]) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "JJ(0)").WithArguments("JJ", "1"), // (22,32): warning CS0067: The event 'Test.E4' is never used // public event System.Action E4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("Test.E4"), // (18,32): warning CS0067: The event 'Test.E2' is never used // public event System.Action E2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("Test.E2"), // (20,32): warning CS0067: The event 'Test.E3' is never used // public event System.Action E3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("Test.E3"), // (16,32): warning CS0067: The event 'Test.E1' is never used // public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("Test.E1")); } [Fact] public void TestAttributesOnIndexer_NoDuplicateDiagnostics() { string source = @" public class AA : System.Attribute { } public class BB : System.Attribute { } public class CC : System.Attribute { } public class DD : System.Attribute { } public class EE : System.Attribute { } public class Test { public int this[[AA(0)]int x] { [return: BB(0)] [CC(0)] get { return x; } [param: DD(0)] [EE(0)] set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1729: 'AA' does not contain a constructor that takes 1 arguments // public int this[[AA(0)]int x] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "AA(0)").WithArguments("AA", "1"), // (13,10): error CS1729: 'CC' does not contain a constructor that takes 1 arguments // [CC(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "CC(0)").WithArguments("CC", "1"), // (12,18): error CS1729: 'BB' does not contain a constructor that takes 1 arguments // [return: BB(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "BB(0)").WithArguments("BB", "1"), // (16,17): error CS1729: 'DD' does not contain a constructor that takes 1 arguments // [param: DD(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "DD(0)").WithArguments("DD", "1"), // (17,10): error CS1729: 'EE' does not contain a constructor that takes 1 arguments // [EE(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "EE(0)").WithArguments("EE", "1")); } private static string GetSingleAttributeName(Symbol symbol) { return symbol.GetAttributes().Single().AttributeClass.Name; } private static void AssertNoAttributes(Symbol symbol) { Assert.Equal(0, symbol.GetAttributes().Length); } [Fact] public void TestAttributesOnDelegates() { string source = @" using System; public class TypeAttribute : System.Attribute { } public class ParamAttribute : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute] [return: ReturnTypeAttribute] public delegate T Delegate<[TypeParamAttribute]T> ([ParamAttribute]T p1, [param: ParamAttribute]ref T p2, [ParamAttribute]out T p3); public delegate int Delegate2 ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate<int>).GetCustomAttributes(false); } }"; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var typeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeAttribute"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); var returnTypeAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ReturnTypeAttribute"); var typeParamAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); Assert.Equal(1, delegateType.GetAttributes(typeAttrType).Count()); // Verify type parameter attribute var typeParameters = delegateType.TypeParameters; Assert.Equal(1, typeParameters.Length); Assert.Equal(1, typeParameters[0].GetAttributes(typeParamAttrType).Count()); // Verify delegate methods (return type/parameters) attributes // Invoke method // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax var invokeMethod = delegateType.GetMethod("Invoke"); Assert.Equal(1, invokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(typeParameters[0], invokeMethod.ReturnType); var parameters = invokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); // Delegate Constructor: // 1) Doesn't have any return type attributes // 2) Doesn't have any parameter attributes var ctor = delegateType.GetMethod(".ctor"); Assert.Equal(0, ctor.GetReturnTypeAttributes().Length); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: // 1) Doesn't have any return type attributes // 2) Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); Assert.Equal(0, beginInvokeMethod.GetReturnTypeAttributes().Length); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(5, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[2].Name); Assert.Equal(1, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[4].GetAttributes(paramAttrType).Count()); // EndInvoke method: // 1) Has return type attributes from delegate declaration syntax // 2) Has parameter attributes from delegate declaration syntax // only for ref/out parameters. var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); Assert.Equal(1, endInvokeMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, returnTypeAttrType, TypeCompareKind.ConsiderEverything2)).Count()); parameters = endInvokeMethod.GetParameters(); Assert.Equal(3, parameters.Length); Assert.Equal("p2", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p3", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); } [Fact] public void TestAttributesOnDelegates_NoDuplicateDiagnostics() { string source = @" public class TypeAttribute : System.Attribute { } public class ParamAttribute1 : System.Attribute { } public class ParamAttribute2 : System.Attribute { } public class ParamAttribute3 : System.Attribute { } public class ParamAttribute4 : System.Attribute { } public class ParamAttribute5 : System.Attribute { } public class ReturnTypeAttribute : System.Attribute { } public class TypeParamAttribute : System.Attribute { } class C { [TypeAttribute(0)] [return: ReturnTypeAttribute(0)] public delegate T Delegate<[TypeParamAttribute(0)]T> ([ParamAttribute1(0)]T p1, [param: ParamAttribute2(0)]ref T p2, [ParamAttribute3(0)]out T p3); public delegate int Delegate2 ([ParamAttribute4(0)]int p1 = 0, [param: ParamAttribute5(0)]params int[] p2); }"; CreateCompilation(source).VerifyDiagnostics( // (13,6): error CS1729: 'TypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeAttribute(0)").WithArguments("TypeAttribute", "1"), // (15,33): error CS1729: 'TypeParamAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "TypeParamAttribute(0)").WithArguments("TypeParamAttribute", "1"), // (15,60): error CS1729: 'ParamAttribute1' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute1(0)").WithArguments("ParamAttribute1", "1"), // (15,93): error CS1729: 'ParamAttribute2' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute2(0)").WithArguments("ParamAttribute2", "1"), // (15,123): error CS1729: 'ParamAttribute3' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute3(0)").WithArguments("ParamAttribute3", "1"), // (14,14): error CS1729: 'ReturnTypeAttribute' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ReturnTypeAttribute(0)").WithArguments("ReturnTypeAttribute", "1"), // (17,37): error CS1729: 'ParamAttribute4' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute4(0)").WithArguments("ParamAttribute4", "1"), // (17,76): error CS1729: 'ParamAttribute5' does not contain a constructor that takes 1 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ParamAttribute5(0)").WithArguments("ParamAttribute5", "1")); } [Fact] public void TestAttributesOnDelegateWithOptionalAndParams() { string source = @" using System; public class ParamAttribute : System.Attribute { } class C { public delegate int Delegate ([ParamAttribute]int p1 = 0, [param: ParamAttribute]params int[] p2); static void Main() { typeof(Delegate).GetCustomAttributes(false); } }"; Func<bool, Action<ModuleSymbol>> symbolValidator = isFromMetadata => moduleSymbol => { var type = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var paramAttrType = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("ParamAttribute"); // Verify delegate type attribute var delegateType = type.GetTypeMember("Delegate"); // Verify delegate methods (return type/parameters) attributes // Invoke method has parameter attributes from delegate declaration syntax var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); var parameters = invokeMethod.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1]); } // Delegate Constructor: Doesn't have any parameter attributes var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); parameters = ctor.GetParameters(); Assert.Equal(2, parameters.Length); Assert.Equal(0, parameters[0].GetAttributes().Length); Assert.Equal(0, parameters[1].GetAttributes().Length); // BeginInvoke method: Has parameter attributes from delegate declaration parameters syntax var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); parameters = beginInvokeMethod.GetParameters(); Assert.Equal(4, parameters.Length); Assert.Equal("p1", parameters[0].Name); Assert.Equal(1, parameters[0].GetAttributes(paramAttrType).Count()); Assert.Equal("p2", parameters[1].Name); Assert.Equal(1, parameters[1].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[2].GetAttributes(paramAttrType).Count()); Assert.Equal(0, parameters[3].GetAttributes(paramAttrType).Count()); if (isFromMetadata) { // verify no ParamArrayAttribute on p2 VerifyParamArrayAttribute(parameters[1], expected: false); } }; CompileAndVerify(source, sourceSymbolValidator: symbolValidator(false), symbolValidator: symbolValidator(true)); } [Fact] public void TestAttributesOnEnumField() { string source = @" using System; using System.Collections.Generic; using System.Reflection; using CustomAttribute; using AN = CustomAttribute.AttrName; // Use AttrName without Attribute suffix [assembly: AN(UShortField = 4321)] [assembly: AN(UShortField = 1234)] // TODO: below attribute seems to be an ambiguous attribute specification // TODO: modify the test assembly to remove ambiguity // [module: AttrName(TypeField = typeof(System.IO.FileStream))] namespace AttributeTest { class Goo { public class NestedClass { // enum as object [AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly | BindingFlags.Public, UIntField = 123 * Field)] internal const uint Field = 10; } [AllInheritMultiple(new char[] { 'q', 'c' }, """")] [AllInheritMultiple()] enum NestedEnum { zero, one = 1, [AllInheritMultiple(null, 256, 0f, -1, AryField = new ulong[] { 0, 1, 12345657 })] [AllInheritMultipleAttribute(typeof(Dictionary<string, int>), 255 + NestedClass.Field, -0.0001f, 3 - (short)NestedEnum.oneagain)] three = 3, oneagain = one } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; var compilation = CreateCompilation(source, references, options: TestOptions.ReleaseDll); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var attrs = m.GetAttributes(); // Assert.Equal(1, attrs.Count); // Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); // attrs[0].VerifyValue<Type>(0, "TypeField", TypedConstantKind.Type, typeof(System.IO.FileStream)); var assembly = m.ContainingSymbol; attrs = assembly.GetAttributes(); Assert.Equal(2, attrs.Length); Assert.Equal("CustomAttribute.AttrName", attrs[0].AttributeClass.ToDisplayString()); attrs[1].VerifyNamedArgumentValue<ushort>(0, "UShortField", TypedConstantKind.Primitive, 1234); var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var top = (NamedTypeSymbol)ns.GetMember("Goo"); var type = top.GetMember<NamedTypeSymbol>("NestedClass"); var field = type.GetMember<FieldSymbol>("Field"); attrs = field.GetAttributes(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs[0].AttributeClass.ToDisplayString()); attrs[0].VerifyValue(0, TypedConstantKind.Enum, (int)FileMode.Open); attrs[0].VerifyValue(1, TypedConstantKind.Enum, (int)(BindingFlags.DeclaredOnly | BindingFlags.Public)); attrs[0].VerifyNamedArgumentValue<uint>(0, "UIntField", TypedConstantKind.Primitive, 1230); var nenum = top.GetMember<TypeSymbol>("NestedEnum"); attrs = nenum.GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue(0, TypedConstantKind.Array, new char[] { 'q', 'c' }); Assert.Equal(SyntaxKind.Attribute, attrs[0].ApplicationSyntaxReference.GetSyntax().Kind()); var syntax = (AttributeSyntax)attrs[0].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(2, syntax.ArgumentList.Arguments.Count()); syntax = (AttributeSyntax)attrs[1].ApplicationSyntaxReference.GetSyntax(); Assert.Equal(0, syntax.ArgumentList.Arguments.Count()); attrs = nenum.GetMember("three").GetAttributes(); Assert.Equal(2, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs[0].VerifyValue<long>(1, TypedConstantKind.Primitive, 256); attrs[0].VerifyValue<float>(2, TypedConstantKind.Primitive, 0); attrs[0].VerifyValue<short>(3, TypedConstantKind.Primitive, -1); attrs[0].VerifyNamedArgumentValue<ulong[]>(0, "AryField", TypedConstantKind.Array, new ulong[] { 0, 1, 12345657 }); attrs[1].VerifyValue<object>(0, TypedConstantKind.Type, typeof(Dictionary<string, int>)); attrs[1].VerifyValue<long>(1, TypedConstantKind.Primitive, 265); attrs[1].VerifyValue<float>(2, TypedConstantKind.Primitive, -0.0001f); attrs[1].VerifyValue<short>(3, TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesOnDelegate() { string source = @" using System; using System.Collections.Generic; using CustomAttribute; namespace AttributeTest { public class Goo { [AllInheritMultiple(new object[] { 0, """", null }, 255, -127 - 1, AryProp = new object[] { new object[] { """", typeof(IList<string>) } })] public delegate void NestedSubDele([AllInheritMultiple()]string p1, [Derived(typeof(string[, ,]))]string p2); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var dele = (NamedTypeSymbol)type.GetTypeMember("NestedSubDele"); var attrs = dele.GetAttributes(); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 0, "", null }); attrs.First().VerifyValue<byte>(1, TypedConstantKind.Primitive, 255); attrs.First().VerifyValue<sbyte>(2, TypedConstantKind.Primitive, -128); attrs.First().VerifyNamedArgumentValue<object[]>(0, "AryProp", TypedConstantKind.Array, new object[] { new object[] { "", typeof(IList<string>) } }); var mem = dele.GetMember<MethodSymbol>("Invoke"); attrs = mem.Parameters[0].GetAttributes(); Assert.Equal(1, attrs.Length); attrs = mem.Parameters[1].GetAttributes(); Assert.Equal(1, attrs.Length); attrs[0].VerifyValue<object>(0, TypedConstantKind.Type, typeof(string[,,])); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesUseBaseAttributeField() { string source = @" using System; namespace AttributeTest { public interface IGoo { [CustomAttribute.Derived(new object[] { 1, null, ""Hi"" }, ObjectField = 2)] int F(int p); } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetMember<MethodSymbol>("F").GetAttributes(); Assert.Equal(@"CustomAttribute.DerivedAttribute({1, null, ""Hi""}, ObjectField = 2)", attrs.First().ToString()); attrs.First().VerifyValue<object>(0, TypedConstantKind.Array, new object[] { 1, null, "Hi" }); attrs.First().VerifyNamedArgumentValue<object>(0, "ObjectField", TypedConstantKind.Primitive, 2); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007a() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Z { public class Attr { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007b() { string source = @" using System; using X; using Z; namespace X { public class AttrAttribute : Attribute { } public class Attr : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("X.AttrAttribute", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007c() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute /*: Attribute*/ { } } namespace Y { public class AttrAttribute /*: Attribute*/ { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); CompileAndVerify(compilation).VerifyDiagnostics(); } [WorkItem(688007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/688007")] [Fact] public void Bug688007d() { string source = @" using System; using X; using Y; using Z; namespace X { public class AttrAttribute : Attribute { } } namespace Y { public class AttrAttribute : Attribute { } } namespace Z { public class Attr : Attribute { } } [Attr()] partial class CDoc { static void Main(string[] args) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var globalNs = compilation.GlobalNamespace; var cDoc = globalNs.GetTypeMember("CDoc"); Assert.NotNull(cDoc); var attrs = cDoc.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Z.Attr", attrs[0].AttributeClass.ToDisplayString()); var syntax = attrs.Single().ApplicationSyntaxReference.GetSyntax(); Assert.NotNull(syntax); Assert.IsType<AttributeSyntax>(syntax); CompileAndVerify(compilation).VerifyDiagnostics(); } [Fact] public void TestAttributesWithParamArrayInCtor01() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' '}, """")] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributesWithParamArrayInCtor02() { string source = @" using System; namespace AttributeTest { class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } class Program { [Example(""MultipleArgumentsToParamsParameter"", 4, 5, 6)] public void MultipleArgumentsToParamsParameter() { } [Example(""NoArgumentsToParamsParameter"")] public void NoArgumentsToParamsParameter() { } [Example(""NullArgumentToParamsParameter"", null)] public void NullArgumentToParamsParameter() { } static void Main() { ExampleAttribute att = null; try { var programType = typeof(Program); var method = programType.GetMember(""MultipleArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NoArgumentsToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; method = programType.GetMember(""NullArgumentToParamsParameter"")[0]; att = (ExampleAttribute)method.GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } } "; Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeClass = (NamedTypeSymbol)ns.GetMember("ExampleAttribute"); var method = (MethodSymbol)type.GetMember("MultipleArgumentsToParamsParameter"); var attrs = method.GetAttributes(attributeClass); var attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "MultipleArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { 4, 5, 6 }); method = (MethodSymbol)type.GetMember("NoArgumentsToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NoArgumentsToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, new int[] { }); method = (MethodSymbol)type.GetMember("NullArgumentToParamsParameter"); attrs = method.GetAttributes(attributeClass); attr = attrs.Single(); Assert.Equal(2, attr.CommonConstructorArguments.Length); attr.VerifyValue<string>(0, TypedConstantKind.Primitive, "NullArgumentToParamsParameter"); attr.VerifyValue<int[]>(1, TypedConstantKind.Array, null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. var compVerifier = CompileAndVerify( source, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator, expectedOutput: "True\r\n", expectedSignatures: new[] { Signature("AttributeTest.Program", "MultipleArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"MultipleArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void MultipleArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NoArgumentsToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NoArgumentsToParamsParameter\", System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeTypedArgument])] public hidebysig instance System.Void NoArgumentsToParamsParameter() cil managed"), Signature("AttributeTest.Program", "NullArgumentToParamsParameter", ".method [AttributeTest.ExampleAttribute(\"NullArgumentToParamsParameter\", )] public hidebysig instance System.Void NullArgumentToParamsParameter() cil managed"), }); } [Fact, WorkItem(531385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531385")] public void TestAttributesWithParamArrayInCtor3() { string source = @" using System; using CustomAttribute; namespace AttributeTest { [AllInheritMultiple(new char[] { ' ' }, new string[] { ""whatever"" })] public interface IGoo { } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> sourceAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); Assert.True(attrs.First().AttributeConstructor.Parameters.Last().IsParams); }; Action<ModuleSymbol> mdAttributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("IGoo"); var attrs = type.GetAttributes(); attrs.First().VerifyValue<char[]>(0, TypedConstantKind.Array, new char[] { ' ' }); attrs.First().VerifyValue<string[]>(1, TypedConstantKind.Array, new string[] { "whatever" }); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: sourceAttributeValidator, symbolValidator: mdAttributeValidator); } [Fact] public void TestAttributeSpecifiedOnItself() { string source = @" using System; namespace AttributeTest { [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("MyAttribute"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); attrs.First().VerifyValue(0, TypedConstantKind.Type, typeof(Object)); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [Fact] public void TestAttributesWithEnumArrayInCtor() { string source = @" using System; namespace AttributeTest { public enum X { a, b }; public class Y : Attribute { public int f; public Y(X[] x) { } } [Y(A.x)] public class A { public const X[] x = null; public static void Main() { } } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Array, (object[])null); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541058")] [Fact] public void TestAttributesWithTypeof() { string source = @" using System; [MyAttribute(typeof(object))] public class MyAttribute : Attribute { public MyAttribute(Type t) { } public static void Main() { } } "; CompileAndVerify(source); } [WorkItem(541071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541071")] [Fact] public void TestAttributesWithParams() { string source = @" using System; class ExampleAttribute : Attribute { public int[] Numbers; public ExampleAttribute(string message, params int[] numbers) { Numbers = numbers; } } [Example(""wibble"", 4, 5, 6)] class Program { static void Main() { ExampleAttribute att = null; try { att = (ExampleAttribute)typeof(Program).GetCustomAttributes(typeof(ExampleAttribute), false)[0]; } catch (Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine(true); } } "; var expectedOutput = @"True"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestAttributesOnReturnType() { string source = @" using System; using CustomAttribute; namespace AttributeTest { public class Goo { int p; public int Property { [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] get { return p; } [return: AllInheritMultipleAttribute()] [AllInheritMultipleAttribute()] set { p = value; } } [return: AllInheritMultipleAttribute()] [return: AllInheritMultipleAttribute()] public int Method() { return p; } [return: AllInheritMultipleAttribute()] public delegate void Delegate(); public static void Main() {} } } "; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Goo"); var property = (PropertySymbol)type.GetMember("Property"); var getter = property.GetMethod; var attrs = getter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var setter = property.SetMethod; attrs = setter.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var method = (MethodSymbol)type.GetMember("Method"); attrs = method.GetReturnTypeAttributes(); Assert.Equal(2, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); attr = attrs.Last(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var delegateType = type.GetTypeMember("Delegate"); var invokeMethod = (MethodSymbol)delegateType.GetMember("Invoke"); attrs = invokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); var ctor = (MethodSymbol)delegateType.GetMember(".ctor"); attrs = ctor.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var beginInvokeMethod = (MethodSymbol)delegateType.GetMember("BeginInvoke"); attrs = beginInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(0, attrs.Length); var endInvokeMethod = (MethodSymbol)delegateType.GetMember("EndInvoke"); attrs = endInvokeMethod.GetReturnTypeAttributes(); Assert.Equal(1, attrs.Length); attr = attrs.First(); Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541397")] [Fact] public void TestAttributeWithSameNameAsTypeParameter() { string source = @" using System; namespace AttributeTest { public class TAttribute : Attribute { } public class RAttribute : TAttribute { } public class GClass<T> { [T] public enum E { } [R] internal R M<R>() { return default(R); } } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("GClass"); var enumType = (NamedTypeSymbol)type.GetTypeMember("E"); var attributeType = (NamedTypeSymbol)ns.GetMember("TAttribute"); var attributeType2 = (NamedTypeSymbol)ns.GetMember("RAttribute"); var genMethod = (MethodSymbol)type.GetMember("M"); var attrs = enumType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs = genMethod.GetAttributes(attributeType2); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void TestAttributeWithVarIdentifierName() { string source = @" using System; namespace AttributeTest { public class var: Attribute { } [var] class Program { public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("Program"); var attributeType = (NamedTypeSymbol)ns.GetMember("var"); var attrs = type.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.var", attr.ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentBind_PropertyWithSameName() { var source = @"using System; namespace AttributeTest { class TestAttribute : Attribute { public TestAttribute(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class TestClass { ProtectionLevel ProtectionLevel { get { return ProtectionLevel.Privacy; } } [TestAttribute(ProtectionLevel.Privacy)] public int testField; } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeType = (NamedTypeSymbol)ns.GetMember("TestAttribute"); var field = (FieldSymbol)type.GetMember("testField"); var attrs = field.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(541709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541709")] [Fact] public void AttributeOnSynthesizedParameterSymbol() { var source = @"using System; namespace AttributeTest { public class TestAttributeForMethod : System.Attribute { } public class TestAttributeForParam : System.Attribute { } public class TestAttributeForReturn : System.Attribute { } class TestClass { int P1 { [TestAttributeForMethod] [param: TestAttributeForParam] [return: TestAttributeForReturn] set { } } int P2 { [TestAttributeForMethod] [return: TestAttributeForReturn] get { return 0; } } public static void Main() {} } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("TestClass"); var attributeTypeForMethod = (NamedTypeSymbol)ns.GetMember("TestAttributeForMethod"); var attributeTypeForParam = (NamedTypeSymbol)ns.GetMember("TestAttributeForParam"); var attributeTypeForReturn = (NamedTypeSymbol)ns.GetMember("TestAttributeForReturn"); var property = (PropertySymbol)type.GetMember("P1"); var setter = property.SetMethod; var attrs = setter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); Assert.Equal(1, setter.ParameterCount); attrs = setter.Parameters[0].GetAttributes(attributeTypeForParam); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForParam", attr.AttributeClass.ToDisplayString()); attrs = setter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); property = (PropertySymbol)type.GetMember("P2"); var getter = property.GetMethod; attrs = getter.GetAttributes(attributeTypeForMethod); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForMethod", attr.AttributeClass.ToDisplayString()); attrs = getter.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, attributeTypeForReturn, TypeCompareKind.ConsiderEverything2)); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal("AttributeTest.TestAttributeForReturn", attr.AttributeClass.ToDisplayString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributeStringForEnumTypedConstant() { var source = CreateCompilationWithMscorlib40(@" using System; namespace AttributeTest { enum X { One = 1, Two = 2, Three = 3 }; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event, Inherited = false, AllowMultiple = true)] class A : System.Attribute { public A(X x) { } public static void Main() { } // AttributeData.ToString() should display 'X.Three' not 'X.One | X.Two' [A(X.Three)] int field; // AttributeData.ToString() should display '5' [A((X)5)] int field2; } } "); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue(0, TypedConstantKind.Enum, (int)(AttributeTargets.Field | AttributeTargets.Event)); Assert.Equal(2, attr.CommonNamedArguments.Length); attr.VerifyNamedArgumentValue(0, "Inherited", TypedConstantKind.Primitive, false); attr.VerifyNamedArgumentValue(1, "AllowMultiple", TypedConstantKind.Primitive, true); Assert.Equal(@"System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Event, Inherited = false, AllowMultiple = true)", attr.ToString()); var fieldSymbol = (FieldSymbol)type.GetMember("field"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(AttributeTest.X.Three)", attrs.First().ToString()); fieldSymbol = (FieldSymbol)type.GetMember("field2"); attrs = fieldSymbol.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal(@"AttributeTest.A(5)", attrs.First().ToString()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [Fact] public void TestAttributesWithNamedConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(y:4, z:5, X = 6)] public class A : Attribute { public int X; public A(int y, int z) { Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithNamedConstructorArguments_02() { string source = @" using System; namespace AttributeTest { [A(3, z:5, y:4, X = 6)] public class A : Attribute { public int X; public A(int x, int y, int z) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541864")] [Fact] public void Bug_8769_TestAttributesWithNamedConstructorArguments() { string source = @" using System; namespace AttributeTest { [A(y: 1, x: 2)] public class A : Attribute { public A(int x, int y) { Console.WriteLine(x); Console.WriteLine(y); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); Assert.Equal(2, attrs.First().CommonConstructorArguments.Length); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 1); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2 1 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [Fact] public void TestAttributesWithOptionalConstructorArguments_01() { string source = @" using System; namespace AttributeTest { [A(3, z:5, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 3); attrs.First().VerifyValue(1, TypedConstantKind.Primitive, 4); attrs.First().VerifyValue(2, TypedConstantKind.Primitive, 5); attrs.First().VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, 6); }; string expectedOutput = @"3 4 5 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541861")] [Fact] public void Bug_8768_TestAttributesWithOptionalConstructorArguments() { string source = @" using System; namespace AttributeTest { [A] public class A : Attribute { public A(int x = 2) { Console.Write(x); } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var ns = (NamespaceSymbol)m.GlobalNamespace.GetMember("AttributeTest"); var type = (NamedTypeSymbol)ns.GetMember("A"); var attrs = type.GetAttributes(); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 2); Assert.Equal(0, attrs.First().CommonNamedArguments.Length); }; string expectedOutput = @"2"; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(541854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541854")] [Fact] public void Bug8761_StringArrayArgument() { var source = @"using System; [A(X = new string[] { """" })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void Bug8763_NullInArrayInitializer() { var source = @"using System; [A(X = new object[] { null })] public class A : Attribute { public object[] X; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); } } [A(X = new object[] { typeof(int), typeof(System.Type), 1, null, ""hi"" })] public class B { public object[] X; } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541856, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541856")] [Fact] public void AttributeArrayTypeArgument() { var source = @"using System; [A(objArray = new string[] { ""a"", null })] public class A : Attribute { public object[] objArray; public object obj; static void Main() { typeof(A).GetCustomAttributes(false); typeof(B).GetCustomAttributes(false); typeof(C).GetCustomAttributes(false); typeof(D).GetCustomAttributes(false); typeof(E).GetCustomAttributes(false); typeof(F).GetCustomAttributes(false); typeof(G).GetCustomAttributes(false); typeof(H).GetCustomAttributes(false); typeof(I).GetCustomAttributes(false); } } [A(objArray = new object[] { ""a"", null, 3 })] public class B { } /* CS0029: Cannot implicitly convert type 'int[]' to 'object[]' [A(objArray = new int[] { 3 })] public class Error { } */ [A(objArray = null)] public class C { } [A(obj = new string[] { ""a"" })] public class D { } [A(obj = new object[] { ""a"", null, 3 })] public class E { } [A(obj = new int[] { 1 })] public class F { } [A(obj = 1)] public class G { } [A(obj = ""a"")] public class H { } [A(obj = null)] public class I { } "; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541859")] [Fact] public void Bug8766_AttributeCtorOverloadResolution() { var source = @"using System; [A(C)] public class A : Attribute { const int C = 1; A(int x) { Console.Write(""int""); } public A(long x) { Console.Write(""long""); } static void Main() { typeof(A).GetCustomAttributes(false); } } "; CompileAndVerify(source, expectedOutput: "int"); } [WorkItem(541876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541876")] [Fact] public void Bug8771_AttributeArgumentNameBinding() { var source = @"using System; public class A : Attribute { public A(int x) { Console.WriteLine(x); } } class B { const int X = 1; [A(X)] class C<[A(X)] T> { const int X = 2; } static void Main() { typeof(C<>).GetCustomAttributes(false); typeof(C<>).GetGenericArguments()[0].GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); var typeParameters = cClass.TypeParameters; Assert.Equal(1, typeParameters.Length); attrs = typeParameters[0].GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Primitive, 2); }; string expectedOutput = @"2 2 "; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithNestedUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>.C))] public class B<T> { public class C { } } public class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = bClass.GetTypeMember("C"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, cClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546380")] [Fact] public void AttributeWithUnboundGenericType() { var source = @"using System; using System.Collections.Generic; public class A : Attribute { public A(object o) { } } [A(typeof(B<>))] public class B<T> { } class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol bClass = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = bClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attrs.First().VerifyValue(0, TypedConstantKind.Type, bClass.AsUnboundGenericType()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(542223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542223")] [Fact] public void AttributeArgumentAsEnumFromMetadata() { var metadataStream1 = CSharpCompilation.Create("bar.dll", references: new[] { MscorlibRef }, syntaxTrees: new[] { Parse("public enum Bar { Baz }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref1 = MetadataReference.CreateFromStream(metadataStream1); var metadataStream2 = CSharpCompilation.Create("goo.dll", references: new[] { MscorlibRef, ref1 }, syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree( "public class Ca : System.Attribute { public Ca(object o) { } } " + "[Ca(Bar.Baz)]" + "public class Goo { }") }).EmitToStream(options: new EmitOptions(metadataOnly: true)); var ref2 = MetadataReference.CreateFromStream(metadataStream2); var compilation = CSharpCompilation.Create("moo.dll", references: new[] { MscorlibRef, ref1, ref2 }); var goo = compilation.GetTypeByMetadataName("Goo"); var ca = goo.GetAttributes().First().CommonConstructorArguments.First(); Assert.Equal("Bar", ca.Type.Name); } [WorkItem(542318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542318")] [Fact] public void AttributeWithDaysOfWeekArgument() { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintaining compatibility with it. var source = @"using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(X = new DayOfWeek())] [A(X = new bool())] [A(X = new sbyte())] [A(X = new byte())] [A(X = new short())] [A(X = new ushort())] [A(X = new int())] [A(X = new uint())] [A(X = new char())] [A(X = new float())] [A(X = new Single())] [A(X = new double())] public class A : Attribute { public object X; const DayOfWeek dayofweek = new DayOfWeek(); const bool b = new bool(); const sbyte sb = new sbyte(); const byte by = new byte(); const short s = new short(); const ushort us = new ushort(); const int i = new int(); const uint ui = new uint(); const char c = new char(); const float f = new float(); const Single si = new Single(); const double d = new double(); public static void Main() { typeof(A).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(12, attrs.Count()); var enumerator = attrs.GetEnumerator(); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Enum, (int)new DayOfWeek()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new bool()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new sbyte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new byte()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new short()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new ushort()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new int()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new uint()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new char()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new float()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new Single()); enumerator.MoveNext(); enumerator.Current.VerifyNamedArgumentValue(0, "X", TypedConstantKind.Primitive, new double()); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration() { var source = @" using System; class A : Attribute { } partial class Program { [A] static partial void Goo(); static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542534")] [Fact] public void AttributeOnDefiningPartialMethodDeclaration_02() { var source1 = @" using System; class A1 : Attribute {} class B1 : Attribute {} class C1 : Attribute {} class D1 : Attribute {} class E1 : Attribute {} partial class Program { [A1] [return: B1] static partial void Goo<[C1] T, [D1] U>([E1]int x); } "; var source2 = @" using System; class A2 : Attribute {} class B2 : Attribute {} class C2 : Attribute {} class D2 : Attribute {} class E2 : Attribute {} partial class Program { [A2] [return: B2] static partial void Goo<[C2] U, [D2] T>([E2]int y) { } static void Main() {} } "; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var programClass = m.GlobalNamespace.GetTypeMember("Program"); var gooMethod = (MethodSymbol)programClass.GetMember("Goo"); TestAttributeOnPartialMethodHelper(m, gooMethod); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } private void TestAttributeOnPartialMethodHelper(ModuleSymbol m, MethodSymbol gooMethod) { var a1Class = m.GlobalNamespace.GetTypeMember("A1"); var a2Class = m.GlobalNamespace.GetTypeMember("A2"); var b1Class = m.GlobalNamespace.GetTypeMember("B1"); var b2Class = m.GlobalNamespace.GetTypeMember("B2"); var c1Class = m.GlobalNamespace.GetTypeMember("C1"); var c2Class = m.GlobalNamespace.GetTypeMember("C2"); var d1Class = m.GlobalNamespace.GetTypeMember("D1"); var d2Class = m.GlobalNamespace.GetTypeMember("D2"); var e1Class = m.GlobalNamespace.GetTypeMember("E1"); var e2Class = m.GlobalNamespace.GetTypeMember("E2"); Assert.Equal(1, gooMethod.GetAttributes(a1Class).Count()); Assert.Equal(1, gooMethod.GetAttributes(a2Class).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b1Class, TypeCompareKind.ConsiderEverything2)).Count()); Assert.Equal(1, gooMethod.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, b2Class, TypeCompareKind.ConsiderEverything2)).Count()); var typeParam1 = gooMethod.TypeParameters[0]; Assert.Equal(1, typeParam1.GetAttributes(c1Class).Count()); Assert.Equal(1, typeParam1.GetAttributes(c2Class).Count()); var typeParam2 = gooMethod.TypeParameters[1]; Assert.Equal(1, typeParam2.GetAttributes(d1Class).Count()); Assert.Equal(1, typeParam2.GetAttributes(d2Class).Count()); var param = gooMethod.Parameters[0]; Assert.Equal(1, param.GetAttributes(e1Class).Count()); Assert.Equal(1, param.GetAttributes(e2Class).Count()); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_Type() { var source1 = @" using System; class A : Attribute {} [A] partial class X {}"; var source2 = @" using System; class B : Attribute {} [B] partial class X {} class C { public static void Main() { typeof(X).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("X"); Assert.Equal(2, type.GetAttributes().Length); Assert.Equal(1, type.GetAttributes(aClass).Count()); Assert.Equal(1, type.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void AttributesInMultiplePartialDeclarations_TypeParam() { var source1 = @" using System; class A : Attribute {} partial class Gen<[A] T> {}"; var source2 = @" using System; class B : Attribute {} partial class Gen<[B] T> {} class C { public static void Main() {} }"; var compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { var aClass = m.GlobalNamespace.GetTypeMember("A"); var bClass = m.GlobalNamespace.GetTypeMember("B"); var type = m.GlobalNamespace.GetTypeMember("Gen"); var typeParameter = type.TypeParameters.First(); Assert.Equal(2, typeParameter.GetAttributes().Length); Assert.Equal(1, typeParameter.GetAttributes(aClass).Count()); Assert.Equal(1, typeParameter.GetAttributes(bClass).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542550")] [Fact] public void Bug9824() { var source = @" using System; public class TAttribute : Attribute { public static void Main () {} } [T] public class GClass<T> where T : Attribute { [T] public enum E { } } "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("TAttribute"); NamedTypeSymbol GClass = m.GlobalNamespace.GetTypeMember("GClass").AsUnboundGenericType(); Assert.Equal(1, GClass.GetAttributes(attributeType).Count()); NamedTypeSymbol enumE = GClass.GetTypeMember("E"); Assert.Equal(1, enumE.GetAttributes(attributeType).Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_01() { var source = @" using System; [A] public class A : Attribute { public A(object a = default(A)) { } } [A(1)] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); var attrs = attributeType.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attrs = cClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<int>(0, TypedConstantKind.Primitive, 1); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(543135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543135")] [Fact] public void AttributeAndDefaultValueArguments_02() { var source = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class A : System.Attribute { public A(object o = null) { } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class B : System.Attribute { public B(object o = default(B)) { } } [A] [A(null)] [B] [B(default(B))] class C { public static void Main() { typeof(C).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeTypeA = m.GlobalNamespace.GetTypeMember("A"); NamedTypeSymbol attributeTypeB = m.GlobalNamespace.GetTypeMember("B"); NamedTypeSymbol cClass = m.GlobalNamespace.GetTypeMember("C"); // Verify A attributes var attrs = cClass.GetAttributes(attributeTypeA); Assert.Equal(2, attrs.Count()); var attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); // Verify B attributes attrs = cClass.GetAttributes(attributeTypeB); Assert.Equal(2, attrs.Count()); attr = attrs.First(); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); attr = attrs.ElementAt(1); Assert.Equal(1, attr.CommonConstructorArguments.Length); attr.VerifyValue<object>(0, TypedConstantKind.Primitive, null); }; string expectedOutput = ""; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: expectedOutput); } [WorkItem(529044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529044")] [Fact] public void AttributeNameLookup() { var source = @" using System; public class MyClass<T> { } public class MyClassAttribute : Attribute { } [MyClass] public class Test { public static void Main() { typeof(Test).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol attributeType = m.GlobalNamespace.GetTypeMember("MyClassAttribute"); NamedTypeSymbol testClass = m.GlobalNamespace.GetTypeMember("Test"); // Verify attributes var attrs = testClass.GetAttributes(attributeType); Assert.Equal(1, attrs.Count()); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: null, expectedOutput: ""); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void Bug8956_NullArgumentToSystemTypeParam() { string source = @" using System; class A : Attribute { public A(System.Type t) {} } [A(null)] class Test { static void Main(string[] args) { typeof(Test).GetCustomAttributes(false); } } "; CompileAndVerify(source); } [Fact] public void SpecialNameAttributeFromSource() { string source = @" using System; using System.Runtime.CompilerServices; [SpecialName()] public struct S { [SpecialName] byte this[byte x] { get { return x; } } [SpecialName] public event Action<string> E; } "; var comp = CreateCompilation(source); var global = comp.SourceModule.GlobalNamespace; var typesym = global.GetMember("S") as NamedTypeSymbol; Assert.NotNull(typesym); Assert.True(typesym.HasSpecialName); var idxsym = typesym.GetMember(WellKnownMemberNames.Indexer) as PropertySymbol; Assert.NotNull(idxsym); Assert.True(idxsym.HasSpecialName); var etsym = typesym.GetMember("E") as EventSymbol; Assert.NotNull(etsym); Assert.True(etsym.HasSpecialName); } [WorkItem(546277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546277")] [Fact] public void TestArrayTypeInAttributeArgument() { var source = @"using System; public class W {} public class Y<T> { public class F {} public class Z<U> {} } public class X : Attribute { public X(Type y) { } } [X(typeof(W[]))] public class C1 {} [X(typeof(W[,]))] public class C2 {} [X(typeof(W[,][]))] public class C3 {} [X(typeof(Y<W>[][,]))] public class C4 {} [X(typeof(Y<int>.F[,][][,,]))] public class C5 {} [X(typeof(Y<int>.Z<W>[,][]))] public class C6 {} "; var compilation = CreateCompilation(source); Action<ModuleSymbol> attributeValidator = (ModuleSymbol m) => { NamedTypeSymbol classW = m.GlobalNamespace.GetTypeMember("W"); NamedTypeSymbol classY = m.GlobalNamespace.GetTypeMember("Y"); NamedTypeSymbol classF = classY.GetTypeMember("F"); NamedTypeSymbol classZ = classY.GetTypeMember("Z"); NamedTypeSymbol classX = m.GlobalNamespace.GetTypeMember("X"); NamedTypeSymbol classC1 = m.GlobalNamespace.GetTypeMember("C1"); NamedTypeSymbol classC2 = m.GlobalNamespace.GetTypeMember("C2"); NamedTypeSymbol classC3 = m.GlobalNamespace.GetTypeMember("C3"); NamedTypeSymbol classC4 = m.GlobalNamespace.GetTypeMember("C4"); NamedTypeSymbol classC5 = m.GlobalNamespace.GetTypeMember("C5"); NamedTypeSymbol classC6 = m.GlobalNamespace.GetTypeMember("C6"); var attrs = classC1.GetAttributes(); Assert.Equal(1, attrs.Length); var typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC2.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC3.GetAttributes(); Assert.Equal(1, attrs.Length); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classW)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC4.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfW = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(classYOfW), rank: 2); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC5.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol classYOfInt = classY.ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32)))); NamedTypeSymbol substNestedF = classYOfInt.GetTypeMember("F"); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedF), rank: 3); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); attrs = classC6.GetAttributes(); Assert.Equal(1, attrs.Length); NamedTypeSymbol substNestedZ = classYOfInt.GetTypeMember("Z").ConstructIfGeneric(ImmutableArray.Create(TypeWithAnnotations.Create(classW))); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(substNestedZ)); typeArg = ArrayTypeSymbol.CreateCSharpArray(m.ContainingAssembly, TypeWithAnnotations.Create(typeArg), rank: 2); attrs.First().VerifyValue<object>(0, TypedConstantKind.Type, typeArg); }; // Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator: attributeValidator, symbolValidator: attributeValidator); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void TestUnicodeAttributeArgument_Bug16353() { var source = @"using System; [Obsolete(UnicodeHighSurrogate)] class C { public const string UnicodeHighSurrogate = ""\uD800""; public const string UnicodeReplacementCharacter = ""\uFFFD""; static void Main() { string message = ((ObsoleteAttribute)typeof(C).GetCustomAttributes(false)[0]).Message; Console.WriteLine(message == UnicodeReplacementCharacter + UnicodeReplacementCharacter); } }"; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(546621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546621")] [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/41280")] public void TestUnicodeAttributeArgumentsStrings() { string HighSurrogateCharacter = "\uD800"; string LowSurrogateCharacter = "\uDC00"; string UnicodeReplacementCharacter = "\uFFFD"; string UnicodeLT0080 = "\u007F"; string UnicodeLT0800 = "\u07FF"; string UnicodeLT10000 = "\uFFFF"; string source = @" using System; public class C { public const string UnicodeSurrogate1 = ""\uD800""; public const string UnicodeSurrogate2 = ""\uD800\uD800""; public const string UnicodeSurrogate3 = ""\uD800\uDC00""; public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; [Obsolete(UnicodeSurrogate1)] public int x1; [Obsolete(UnicodeSurrogate2)] public int x2; [Obsolete(UnicodeSurrogate3)] public int x3; [Obsolete(UnicodeSurrogate4)] public int x4; [Obsolete(UnicodeSurrogate5)] public int x5; [Obsolete(UnicodeSurrogate6)] public int x6; [Obsolete(UnicodeSurrogate7)] public int x7; [Obsolete(UnicodeSurrogate8)] public int x8; [Obsolete(UnicodeSurrogate9)] public int x9; } "; Action<FieldSymbol, string> VerifyAttributes = (field, value) => { var attributes = field.GetAttributes(); Assert.Equal(1, attributes.Length); attributes[0].VerifyValue(0, TypedConstantKind.Primitive, value); }; Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol module) => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var x1 = type.GetMember<FieldSymbol>("x1"); var x2 = type.GetMember<FieldSymbol>("x2"); var x3 = type.GetMember<FieldSymbol>("x3"); var x4 = type.GetMember<FieldSymbol>("x4"); var x5 = type.GetMember<FieldSymbol>("x5"); var x6 = type.GetMember<FieldSymbol>("x6"); var x7 = type.GetMember<FieldSymbol>("x7"); var x8 = type.GetMember<FieldSymbol>("x8"); var x9 = type.GetMember<FieldSymbol>("x9"); // public const string UnicodeSurrogate1 = ""\uD800""; VerifyAttributes(x1, isFromSource ? HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate2 = ""\uD800\uD800""; VerifyAttributes(x2, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate3 = ""\uD800\uDC00""; VerifyAttributes(x3, HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate4 = ""\uD800\u07FF\uD800""; VerifyAttributes(x4, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + HighSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate5 = ""\uD800\u007F\uDC00""; VerifyAttributes(x5, isFromSource ? HighSurrogateCharacter + UnicodeLT0080 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0080 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate6 = ""\uD800\u07FF\uDC00""; VerifyAttributes(x6, isFromSource ? HighSurrogateCharacter + UnicodeLT0800 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT0800 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate7 = ""\uD800\uFFFF\uDC00""; VerifyAttributes(x7, isFromSource ? HighSurrogateCharacter + UnicodeLT10000 + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeLT10000 + UnicodeReplacementCharacter + UnicodeReplacementCharacter); // public const string UnicodeSurrogate8 = ""\uD800\uD800\uDC00""; VerifyAttributes(x8, isFromSource ? HighSurrogateCharacter + HighSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + HighSurrogateCharacter + LowSurrogateCharacter); // public const string UnicodeSurrogate9 = ""\uDC00\uDC00""; VerifyAttributes(x9, isFromSource ? LowSurrogateCharacter + LowSurrogateCharacter : UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter + UnicodeReplacementCharacter); }; CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false)); } [Fact] [WorkItem(546896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546896")] public void MissingTypeInSignature() { string lib1 = @" public enum E { A, B, C } "; string lib2 = @" public class A : System.Attribute { public A(E e) { } } public class C { [A(E.A)] public void M() { } } "; string main = @" class D : C { void N() { M(); } } "; var c1 = CreateCompilation(lib1); var r1 = c1.EmitToImageReference(); var c2 = CreateCompilation(lib2, references: new[] { r1 }); var r2 = c2.EmitToImageReference(); var cm = CreateCompilation(main, new[] { r2 }); cm.VerifyDiagnostics(); var model = cm.GetSemanticModel(cm.SyntaxTrees[0]); int index = main.IndexOf("M()", StringComparison.Ordinal); var m = (ExpressionSyntax)cm.SyntaxTrees[0].GetCompilationUnitRoot().FindToken(index).Parent.Parent; var info = model.GetSymbolInfo(m); var args = info.Symbol.GetAttributes()[0].CommonConstructorArguments; // unresolved type - parameter ignored Assert.Equal(0, args.Length); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089")] public void NullArrays() { var source = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); }); } [Fact] public void NullTypeAndString() { var source = @" using System; public class A : Attribute { public A(Type t, string s) { } } [A(null, null)] class C { } "; CompileAndVerify(source, symbolValidator: (m) => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.Null(args[0].Value); Assert.Equal("Type", args[0].Type.Name); Assert.Throws<InvalidOperationException>(() => args[0].Values); Assert.Null(args[1].Value); Assert.Equal("String", args[1].Type.Name); Assert.Throws<InvalidOperationException>(() => args[1].Values); }); } [WorkItem(121, "https://github.com/dotnet/roslyn/issues/121")] [Fact] public void Bug_AttributeOnWrongGenericParameter() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; CompileAndVerify(source, symbolValidator: module => { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var classTypeParameter = @class.TypeParameters.Single(); var method = @class.GetMember<MethodSymbol>("M"); var methodTypeParameter = method.TypeParameters.Single(); Assert.Empty(classTypeParameter.GetAttributes()); var attribute = methodTypeParameter.GetAttributes().Single(); Assert.Equal("XAttribute", attribute.AttributeClass.Name); }); } #endregion #region Error Tests [Fact] public void AttributeConstructorErrors1() { var compilation = CreateCompilationWithMscorlib40AndSystemCore(@" using System; static class m { public static int NotAConstant() { return 9; } } public enum e1 { a } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public XAttribute() { } public XAttribute(decimal d) { } public XAttribute(ref int i) { } public XAttribute(e1 e) { } } [XDoesNotExist()] [X(1m)] [X(1)] [X(e1.a)] [X(A.dyn)] [X(m.NotAConstant() + 2)] class A { public const dynamic dyn = null; } ", options: TestOptions.ReleaseDll); // Note that the dev11 compiler produces errors that XDoesNotExist *and* XDoesNotExistAttribute could not be found. // It does not go on to produce the other errors. compilation.VerifyDiagnostics( // (33,2): error CS0246: The type or namespace name 'XDoesNotExistAttribute' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExistAttribute").WithLocation(33, 2), // (33,2): error CS0246: The type or namespace name 'XDoesNotExist' could not be found (are you missing a using directive or an assembly reference?) // [XDoesNotExist()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "XDoesNotExist").WithArguments("XDoesNotExist").WithLocation(33, 2), // (34,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1m)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(34, 2), // (35,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(1)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(35, 2), // (37,2): error CS0121: The call is ambiguous between the following methods or properties: 'XAttribute.XAttribute(ref int)' and 'XAttribute.XAttribute(e1)' // [X(A.dyn)] Diagnostic(ErrorCode.ERR_AmbigCall, "X(A.dyn)").WithArguments("XAttribute.XAttribute(ref int)", "XAttribute.XAttribute(e1)").WithLocation(37, 2), // (38,2): error CS0181: Attribute constructor parameter 'd' has type 'decimal', which is not a valid attribute parameter type // [X(m.NotAConstant() + 2)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "X").WithArguments("d", "decimal").WithLocation(38, 2)); } [Fact] public void AttributeNamedArgumentErrors1() { var compilation = CreateCompilation(@" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class XAttribute : Attribute { public void F1(int i) { } private int PrivateField; public static int SharedProperty { get; set; } public int? ReadOnlyProperty { get { return null; } } public decimal BadDecimalType { get; set; } public System.DateTime BadDateType { get; set; } public Attribute[] BadArrayType { get; set; } } [X(NotFound = null)] [X(F1 = null)] [X(PrivateField = null)] [X(SharedProperty = null)] [X(ReadOnlyProperty = null)] [X(BadDecimalType = null)] [X(BadDateType = null)] [X(BadArrayType = null)] class A { } ", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (21,4): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // [X(NotFound = null)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound"), // (22,4): error CS0617: 'F1' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(F1 = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "F1").WithArguments("F1"), // (23,4): error CS0122: 'XAttribute.PrivateField' is inaccessible due to its protection level // [X(PrivateField = null)] Diagnostic(ErrorCode.ERR_BadAccess, "PrivateField").WithArguments("XAttribute.PrivateField"), // (24,4): error CS0617: 'SharedProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(SharedProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "SharedProperty").WithArguments("SharedProperty"), // (25,4): error CS0617: 'ReadOnlyProperty' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [X(ReadOnlyProperty = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ReadOnlyProperty").WithArguments("ReadOnlyProperty"), // (26,4): error CS0655: 'BadDecimalType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDecimalType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDecimalType").WithArguments("BadDecimalType"), // (27,4): error CS0655: 'BadDateType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadDateType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadDateType").WithArguments("BadDateType"), // (28,4): error CS0655: 'BadArrayType' is not a valid named attribute argument because it is not a valid attribute parameter type // [X(BadArrayType = null)] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "BadArrayType").WithArguments("BadArrayType")); } [Fact] public void AttributeNoMultipleAndInvalidTarget() { string source = @" using CustomAttribute; [Base(1)] [@BaseAttribute(""SOS"")] static class AttributeMod { [Derived('Q')] [Derived('C')] public class Goo { } [BaseAttribute(1)] [Base("""")] public class Bar { } }"; var references = new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull()) }; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, references, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'BaseAttribute' attribute // [@BaseAttribute("SOS")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "@BaseAttribute").WithArguments("BaseAttribute").WithLocation(4, 2), // (7,6): error CS0592: Attribute 'Derived' is not valid on this declaration type. It is only valid on 'struct, method, parameter' declarations. // [Derived('Q')] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Derived").WithArguments("Derived", "struct, method, parameter").WithLocation(7, 6), // (8,6): error CS0579: Duplicate 'Derived' attribute // [Derived('C')] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Derived").WithArguments("Derived").WithLocation(8, 6), // (13,6): error CS0579: Duplicate 'Base' attribute // [Base("")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Base").WithArguments("Base").WithLocation(13, 6)); } [Fact] public void AttributeAmbiguousSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Error: Ambiguous class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Refers to X class Class3 { } [@XAttribute] // Refers to XAttribute class Class4 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS1614: 'X' is ambiguous between 'X' and 'XAttribute'; use either '@X' or 'XAttribute' // [X] // Error: Ambiguous Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "X").WithArguments("X", "X", "XAttribute").WithLocation(10, 2)); } [Fact] public void AttributeErrorVerbatimIdentifierInSpecification() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [X] // Refers to X class Class1 { } [XAttribute] // Refers to XAttribute class Class2 { } [@X] // Error: No attribute named X class Class3 { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,2): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // [@X] // Error: No attribute named X Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@X").WithArguments("X").WithLocation(13, 2)); } [Fact] public void AttributeOpenTypeInAttribute() { string source = @" using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { public XAttribute(Type t) { } } class G<T> { [X(typeof(T))] T t1; // Error: open type in attribute [X(typeof(List<T>))] T t2; // Error: open type in attribute } class X { [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (13,8): error CS0416: 'T': an attribute argument cannot use type parameters // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(T)").WithArguments("T"), // (14,8): error CS0416: 'System.Collections.Generic.List<T>': an attribute argument cannot use type parameters // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(List<T>)").WithArguments("System.Collections.Generic.List<T>"), // (13,22): warning CS0169: The field 'G<T>.t1' is never used // [X(typeof(T))] T t1; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t1").WithArguments("G<T>.t1"), // (14,28): warning CS0169: The field 'G<T>.t2' is never used // [X(typeof(List<T>))] T t2; // Error: open type in attribute Diagnostic(ErrorCode.WRN_UnreferencedField, "t2").WithArguments("G<T>.t2"), // (19,32): warning CS0169: The field 'X.x' is never used // [X(typeof(List<int>))] int x; // okay: X refers to XAttribute and List<int> is a closed constructed type Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("X.x"), // (20,29): warning CS0169: The field 'X.y' is never used // [X(typeof(List<>))] int y; // okay: X refers to XAttribute and List<> is an unbound generic type Diagnostic(ErrorCode.WRN_UnreferencedField, "y").WithArguments("X.y") ); } [WorkItem(540924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540924")] [Fact] public void AttributeEnumsAsAttributeParameters() { string source = @" using System; class EClass { public enum EEK { a, b, c, d }; } [AttributeUsage(AttributeTargets.Class)] internal class HelpAttribute : Attribute { public HelpAttribute(EClass.EEK[] b1) { } } [HelpAttribute(new EClass.EEK[2] { EClass.EEK.b, EClass.EEK.c })] public class MainClass { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifier() { string source = @" using System; // Below attribute specification generates a warning regarding invalid target specifier, // We skip binding the attribute with invalid target specifier, // no error generated for invalid use of AttributeUsage on non attribute class. [method: AttributeUsage(AttributeTargets.All)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,2): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "type")); } [WorkItem(768798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768798")] [Fact(Skip = "768798")] public void AttributeInvalidTargetSpecifierOnInvalidAttribute() { string source = @" [method: OopsForgotToBindThis(Haha)] class X { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(/*CS0657, CS0246*/); } [Fact] public void AttributeUsageMultipleErrors() { string source = @"using System; class A { [AttributeUsage(AttributeTargets.Method)] void M1() { } [AttributeUsage(0)] void M2() { } } [AttributeUsage(0)] class B { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(4, 6), // (6,6): error CS0592: Attribute 'AttributeUsage' is not valid on this declaration type. It is only valid on 'class' declarations. // [AttributeUsage(0)] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "AttributeUsage").WithArguments("AttributeUsage", "class").WithLocation(6, 6), // (9,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(9, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { string source = @" using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(3, 39), // (3,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(3, 2) ); } [WorkItem(541059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541059")] [Fact] public void AttributeUsageIsNull() { string source = @" using System; [AttributeUsage(null)] public class Att1 : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } [WorkItem(541072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541072")] [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } /// <summary> /// Bug 7620: System.Nullreference Exception throws while the value of parameter AttributeUsage Is Null /// </summary> [Fact] public void CS1502ERR_NullAttributeUsageArgument() { string source = @" using System; [AttributeUsage(null)] public class Attr : Attribute { } public class Goo { public static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,17): error CS1503: Argument 1: cannot convert from '<null>' to 'System.AttributeTargets' // [AttributeUsage(null)] Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "System.AttributeTargets")); } /// <summary> /// Bug 7632: Debug.Assert() Failure while Attribute Contains Generic /// </summary> [Fact] public void CS0404ERR_GenericAttributeError() { string source = @" [Goo<int>] class G { } class Goo<T> { } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2), // (2,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Goo<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Goo<int>").WithArguments("generic attributes").WithLocation(2, 2)); compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultipleSyntaxTrees() { var source1 = @"using System; [module: A] [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { }"; var source2 = @"[module: B]"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (2,10): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(2, 10), // (1,10): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 10)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultipleSyntaxTrees_TypeParam() { var source1 = @"using System; [AttributeUsage(AttributeTargets.Class)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } class Gen<[A] T> {} "; var source2 = @"class Gen2<[B] T> {}"; var compilation = CreateCompilation(new[] { source1, source2 }); compilation.VerifyDiagnostics( // (11,12): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'class' declarations. // class Gen<[A] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "class").WithLocation(11, 12), // (1,13): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // class Gen2<[B] T> {} Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(1, 13)); } [WorkItem(541423, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541423")] [Fact] public void ErrorsInMultiplePartialDeclarations() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } [A] partial class C { } [B] partial class C { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (10,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(10, 2), // (14,2): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 2)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void ErrorsInMultiplePartialDeclarations_TypeParam() { var source = @"using System; [AttributeUsage(AttributeTargets.Struct)] class A : Attribute { } [AttributeUsage(AttributeTargets.Method)] class B : Attribute { } partial class Gen<[A] T> { } partial class Gen<[B] T> { }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,20): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'struct' declarations. // partial class Gen<[A] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "struct").WithLocation(11, 20), // (14,20): error CS0592: Attribute 'B' is not valid on this declaration type. It is only valid on 'method' declarations. // partial class Gen<[B] T> Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "B").WithArguments("B", "method").WithLocation(14, 20)); } [WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] [Fact] public void AttributeArgumentError_CS0120() { var source = @"using System; class A : Attribute { public A(ProtectionLevel p){} } enum ProtectionLevel { Privacy = 0 } class F { int ProtectionLevel; [A(ProtectionLevel.Privacy)] public int test; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,6): error CS0120: An object reference is required for the non-static field, method, or property 'F.ProtectionLevel' // [A(ProtectionLevel.Privacy)] Diagnostic(ErrorCode.ERR_ObjectRequired, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (14,7): warning CS0169: The field 'F.ProtectionLevel' is never used // int ProtectionLevel; Diagnostic(ErrorCode.WRN_UnreferencedField, "ProtectionLevel").WithArguments("F.ProtectionLevel"), // (17,14): warning CS0649: Field 'F.test' is never assigned to, and will always have its default value 0 // public int test; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "test").WithArguments("F.test", "0") ); } [Fact, WorkItem(541427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541427")] public void AttributeTargetsString() { var source = @" using System; [AttributeUsage(AttributeTargets.All & ~AttributeTargets.Class)] class A : Attribute { } [A] class C { } "; CreateCompilation(source).VerifyDiagnostics( // (3,2): error CS0592: Attribute 'A' is not valid on this declaration type. It is only valid on 'assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter' declarations. // [A] class C { } Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "A").WithArguments("A", "assembly, module, struct, enum, constructor, method, property, indexer, field, event, interface, parameter, delegate, return, type parameter") ); } [Fact] public void AttributeTargetsAssemblyModule() { var source = @" using System; [module: Attr()] [AttributeUsage(AttributeTargets.Assembly)] class Attr: Attribute { public Attr(){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,10): error CS0592: Attribute 'Attr' is not valid on this declaration type. It is only valid on 'assembly' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Attr").WithArguments("Attr", "assembly")); } [WorkItem(541259, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541259")] [Fact] public void CS0182_NonConstantArrayCreationAttributeArgument() { var source = @"using System; [A(new int[1] {Program.f})] // error [A(new int[1])] // error [A(new int[1,1])] // error [A(new int[1 - 1])] // OK create an empty array [A(new A[0])] // error class Program { static public int f = 10; public static void Main() { typeof(Program).GetCustomAttributes(false); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (3,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1] {Program.f})] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Program.f"), // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1]"), // (5,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[1,1])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[1,1]"), // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new A[0])] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new A[0]")); } [WorkItem(541753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541753")] [Fact] public void CS0182_NestedArrays() { var source = @" using System; [A(new int[][] { new int[] { 1 } })] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } class A : Attribute { public A(object x) { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new int[][] { new int[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new int[][] { new int[] { 1 } }").WithLocation(4, 4)); } [WorkItem(541849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541849")] [Fact] public void CS0182_MultidimensionalArrays() { var source = @"using System; class MyAttribute : Attribute { public MyAttribute(params int[][,] x) { } } [My] class Program { static void Main() { typeof(Program).GetCustomAttributes(false); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,2): error CS0181: Attribute constructor parameter 'x' has type 'int[][*,*]', which is not a valid attribute parameter type // [My] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "int[][*,*]").WithLocation(8, 2)); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void AttributeDefaultValueArgument() { var source = @"using System; namespace AttributeTest { [A(3, X = 6)] public class A : Attribute { public int X; public A(int x, int y = 4, object a = default(A)) { } static void Main() { typeof(A).GetCustomAttributes(false); } } } "; var compilation = CompileAndVerify(source, expectedOutput: ""); } [WorkItem(541858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541858")] [Fact] public void CS0416_GenericAttributeDefaultValueArgument() { var source = @"using System; public class A : Attribute { public object X; static void Main() { typeof(C<int>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = default(E))] public enum E { } [A(X = typeof(E2))] public enum E2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = default(E))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(14, 12), // (17,12): error CS0416: 'C<T>.E2': an attribute argument cannot use type parameters // [A(X = typeof(E2))] Diagnostic(ErrorCode.ERR_AttrArgWithTypeVars, "typeof(E2)").WithArguments("C<T>.E2").WithLocation(17, 12)); } [WorkItem(541615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541615")] [Fact] public void CS0246_VarAttributeIdentifier() { var source = @" [var()] class Program { public static void Main() {} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'varAttribute' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("varAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // [var()] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "var").WithArguments("var").WithLocation(2, 2)); } [Fact] public void TestAttributesWithInvalidArgumentsOrder() { string source = @" using System; namespace AttributeTest { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [A(3, z: 5, X = 6, y: 1)] [A(3, z: 5, 1)] [A(3, 1, X = 6, z: 5)] [A(X = 6, 0)] [A(X = 6, x: 0)] public class A : Attribute { public int X; public A(int x, int y = 4, int z = 0) { Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } static void Main() { typeof(A).GetCustomAttributes(false); } } public class B { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (7,27): error CS1016: Named attribute argument expected // [A(3, z: 5, X = 6, y: 1)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "1").WithLocation(7, 27), // (8,17): 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. // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "1").WithArguments("7.2").WithLocation(8, 17), // (8,11): error CS8321: Named argument 'z' is used out-of-position but is followed by an unnamed argument // [A(3, z: 5, 1)] Diagnostic(ErrorCode.ERR_BadNonTrailingNamedArgument, "z").WithArguments("z").WithLocation(8, 11), // (9,24): error CS1016: Named attribute argument expected // [A(3, 1, X = 6, z: 5)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "5").WithLocation(9, 24), // (10,15): error CS1016: Named attribute argument expected // [A(X = 6, 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(10, 15), // (11,18): error CS1016: Named attribute argument expected // [A(X = 6, x: 0)] Diagnostic(ErrorCode.ERR_NamedArgumentExpected, "0").WithLocation(11, 18) ); } [WorkItem(541877, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541877")] [Fact] public void Bug8772_TestDelegateAttributeNameBinding() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(Invoke)] delegate void F1(); delegate T F2<[A(Invoke)]T> (); const int Invoke = 1; static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // [A(Invoke)] Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(11, 8), // (14,22): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate T F2<[A(Invoke)]T> (); Diagnostic(ErrorCode.ERR_BadArgType, "Invoke").WithArguments("1", "method group", "int").WithLocation(14, 22)); } [Fact] public void AmbiguousAttributeErrors_01() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS1614: 'Description' is ambiguous between 'ValidWithoutSuffix.Description' and 'ValidWithSuffix.DescriptionAttribute'; use either '@Description' or 'DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Description").WithArguments("Description", "ValidWithoutSuffix.Description", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_02() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_03() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact] public void AmbiguousAttributeErrors_04() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'ValidWithSuffix_And_ValidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "ValidWithSuffix_And_ValidWithoutSuffix.Description", "ValidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'ValidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute", "ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_05() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0616: 'InvalidWithoutSuffix.Description' is not an attribute class // [Description(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Description").WithArguments("InvalidWithoutSuffix.Description"), // (26,6): error CS0616: 'InvalidWithSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_06() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_06 { using InvalidWithSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_07() { string source = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0616: 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' is not an attribute class // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DescriptionAttribute").WithArguments("InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_08() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_08 { using InvalidWithSuffix; using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [Description(null)] public class Test { } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (36,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_And_InvalidWithoutSuffix.Description' and 'InvalidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_And_InvalidWithoutSuffix.Description", "InvalidWithoutSuffix.Description"), // (39,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithSuffix_And_InvalidWithoutSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_09() { string source = @" namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_But_ValidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_09 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix_But_ValidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (31,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.Description' and 'InvalidWithoutSuffix_But_ValidWithSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix_But_ValidWithoutSuffix.Description", "InvalidWithoutSuffix_But_ValidWithSuffix.Description"), // (34,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix_But_ValidWithoutSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_10() { string source = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_10 { using ValidWithoutSuffix; using InvalidWithoutSuffix; [Description(null)] public class Test { public static void Main() {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithoutSuffix.Description' and 'ValidWithoutSuffix.Description' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithoutSuffix.Description", "ValidWithoutSuffix.Description")); } [Fact] public void AmbiguousAttributeErrors_11() { string source = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace TestNamespace_11 { using ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (23,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute"), // (26,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AmbiguousAttributeErrors_12() { string source = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix_But_ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_12 { using InvalidWithoutSuffix_But_ValidWithSuffix; using InvalidWithSuffix; [Description(null)] public class Test { public static void Main() {} } [DescriptionAttribute(null)] public class Test2 { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (30,6): error CS0104: 'DescriptionAttribute' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [DescriptionAttribute(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "DescriptionAttribute").WithArguments("DescriptionAttribute", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute"), // (27,6): error CS0104: 'Description' is an ambiguous reference between 'InvalidWithSuffix.DescriptionAttribute' and 'InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute' // [Description(null)] Diagnostic(ErrorCode.ERR_AmbigContext, "Description").WithArguments("Description", "InvalidWithSuffix.DescriptionAttribute", "InvalidWithoutSuffix_But_ValidWithSuffix.DescriptionAttribute")); } [Fact] public void AliasAttributeName() { var source = @"using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [A]class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,2): error CS1614: 'A' is ambiguous between 'A2' and 'A1'; use either '@A' or 'AAttribute' Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A").WithArguments("A", "A1", "A2").WithLocation(5, 2)); } [WorkItem(542279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542279")] [Fact] public void MethodSignatureAttributes() { var text = @"class A : System.Attribute { public A(object o) { } } class B { } class C { [return: A(new B())] static object F( [A(new B())] object x, [param: A(new B())] object y) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(8, 16), // (10,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(10, 12), // (11,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new B()").WithLocation(11, 19)); } [Fact] public void AttributeDiagnosticsForEachArgument01() { var source = @"using System; public class A : Attribute { public A(object[] a) {} } [A(new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31) ); } [Fact] public void AttributeDiagnosticsForEachArgument02() { var source = @"using System; public class A : Attribute { public A(object[] a, object[] b) {} } [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] class C<T, U> { public enum E {} }"; // Note that we suppress further errors once we have reported a bad attribute argument. CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 19), // (7,31): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 31), // (7,60): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 60), // (7,72): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(new object[] { default(E), default(E) }, new object[] { default(E), default(E) })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(E)").WithLocation(7, 72) ); } [Fact] public void AttributeArgumentDecimalTypeConstant() { var source = @"using System; [A(X = new decimal())] public class A : Attribute { public object X; const decimal y = new decimal(); }"; CreateCompilation(source).VerifyDiagnostics( // (2,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new decimal())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new decimal()").WithLocation(2, 8)); } [WorkItem(542533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542533")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialClass() { string source = @" class A : System.Attribute { } partial class C<T> { } partial class C<[A][A] T> { } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (4,2): error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(qq)] // CS0103 - no 'qq' in scope C(int qq) { } [A(rr)] // CS0103 - no 'rr' in scope void M(int rr) { } int P { [A(value)]set { } } // CS0103 - no 'value' in scope static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,8): error CS0103: The name 'qq' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "qq").WithArguments("qq"), // (14,8): error CS0103: The name 'rr' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "rr").WithArguments("rr"), // (17,16): error CS0103: The name 'value' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "value").WithArguments("value")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>(); Assert.Equal(3, attrArgSyntaxes.Count()); foreach (var argSyntax in attrArgSyntaxes) { var info = semanticModel.GetSymbolInfo(argSyntax.Expression); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void MethodTypeParameterScope() { string source = @" using System; class A : Attribute { public A(int x) { Console.WriteLine(x); } } class C { [A(typeof(T))] // CS0246 - no 'T' in scope void M<T>() { } static void Main() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,15): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "T").WithArguments("T")); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attrArgSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var typeofSyntax = (TypeOfExpressionSyntax)attrArgSyntax.Expression; var typeofArgSyntax = typeofSyntax.Type; Assert.Equal("T", typeofArgSyntax.ToString()); var info = semanticModel.GetSymbolInfo(typeofArgSyntax); Assert.Null(info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnPartialMethod() { string source = @" class A : System.Attribute { } class B : System.Attribute { } partial class C { [return: B] [A] static partial void Goo(); [return: B] [A] static partial void Goo() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // error CS0579: Duplicate 'A' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"A").WithArguments("A"), // error CS0579: Duplicate 'B' attribute Diagnostic(ErrorCode.ERR_DuplicateAttribute, @"B").WithArguments("B")); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnTypeParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo<[A] T>(); static partial void Goo<[A] T>() { } // partial method without implementation, but another method with same name static partial void Goo2<[A] T>(); static void Goo2<[A] T>() { } // partial method without implementation, but another member with same name static partial void Goo3<[A] T>(); private int Goo3; // partial method without implementation static partial void Goo4<[A][A] T>(); // partial methods differing by signature static partial void Goo5<[A] T>(int x); static partial void Goo5<[A] T>(); // partial method without defining declaration static partial void Goo6<[A][A] T>() { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6<T>()' // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6<T>()").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2<[A] T>() { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,34): error CS0579: Duplicate 'A' attribute // static partial void Goo4<[A][A] T>(); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 34), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6<[A][A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (7,30): error CS0579: Duplicate 'A' attribute // static partial void Goo<[A] T>() { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(7, 30), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [WorkItem(542625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542625")] [Fact] public void DuplicateAttributeOnParameterOfPartialMethod() { string source = @" class A : System.Attribute { } partial class C { static partial void Goo([param: A]int y); static partial void Goo([A] int y) { } // partial method without implementation, but another method with same name static partial void Goo2([A] int y); static void Goo2([A] int y) { } // partial method without implementation, but another member with same name static partial void Goo3([A] int y); private int Goo3; // partial method without implementation static partial void Goo4([A][param: A] int y); // partial methods differing by signature static partial void Goo5([A] int y); static partial void Goo5([A] int y, int z); // partial method without defining declaration static partial void Goo6([A][A] int y) { } } "; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (25,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo6(int)' // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo6").WithArguments("C.Goo6(int)").WithLocation(25, 25), // (11,17): error CS0111: Type 'C' already defines a member called 'Goo2' with the same parameter types // static void Goo2([A] int y) { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo2").WithArguments("Goo2", "C").WithLocation(11, 17), // (15,17): error CS0102: The type 'C' already contains a definition for 'Goo3' // private int Goo3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Goo3").WithArguments("C", "Goo3").WithLocation(15, 17), // (18,41): error CS0579: Duplicate 'A' attribute // static partial void Goo4([A][param: A] int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(18, 41), // (25,34): error CS0579: Duplicate 'A' attribute // static partial void Goo6([A][A] int y) { } Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(25, 34), // (6,37): error CS0579: Duplicate 'A' attribute // static partial void Goo([param: A]int y); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "A").WithArguments("A").WithLocation(6, 37), // (15,17): warning CS0169: The field 'C.Goo3' is never used // private int Goo3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Goo3").WithArguments("C.Goo3").WithLocation(15, 17)); } [Fact] public void PartialMethodOverloads() { string source = @" class A : System.Attribute { } partial class C { static partial void F([A] int y); static partial void F(int y, [A]int z); } "; CompileAndVerify(source); } [WorkItem(543456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543456")] [Fact] public void StructLayoutFieldsAreUsed() { var source = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { int a, b, c; }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542662")] [Fact] public void FalseDuplicateOnPartial() { var source = @" using System; class A : Attribute { } partial class Program { static partial void Goo(int x); [A] static partial void Goo(int x) { } static partial void Goo(); [A] static partial void Goo() { } static void Main() { Console.WriteLine(((Action) Goo).Method.GetCustomAttributesData().Count); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542652")] [Fact] public void Bug9958() { var source = @" class A : System.Attribute { } partial class C { static partial void Goo<T,[A] S>(); static partial void Goo<[A]>() { } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt); compilation.VerifyDiagnostics( // (7,32): error CS1001: Identifier expected // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"), // (7,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.Goo<>()' // static partial void Goo<[A]>() { } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "Goo").WithArguments("C.Goo<>()")); } [WorkItem(542909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542909")] [Fact] public void OverriddenPropertyMissingAccessor() { var source = @"using System; class A : Attribute { public virtual int P { get; set; } } class B1 : A { public override int P { get { return base.P; } } } class B2 : A { public override int P { set { } } } [A(P=0)] [B1(P=1)] [B2(P = 2)] class C { }"; CreateCompilation(source).VerifyDiagnostics(); } [WorkItem(542899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542899")] [Fact] public void TwoSyntaxTrees() { var source = @" using System.Reflection; [assembly: AssemblyTitle(""EnterpriseLibraryExtensions"")] "; var source2 = @" using Microsoft.Practices.EnterpriseLibrary.Configuration.Design; using EnterpriseLibraryExtensions; [assembly: ConfigurationDesignManager(typeof(ExtensionDesignManager))] "; var compilation = CreateCompilation(new string[] { source, source2 }); compilation.GetDiagnostics(); } [WorkItem(543785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543785")] [Fact] public void OpenGenericTypesUsedAsAttributeArgs() { var source = @" class Gen<T> { [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; }"; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); compilation.VerifyDiagnostics( // (4,6): error CS0246: The type or namespace name 'TypeAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttributeAttribute").WithLocation(4, 6), // (4,6): error CS0246: The type or namespace name 'TypeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "TypeAttribute").WithArguments("TypeAttribute").WithLocation(4, 6), // (4,27): error CS0246: The type or namespace name 'L1' could not be found (are you missing a using directive or an assembly reference?) // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L1").WithArguments("L1").WithLocation(4, 27), // (4,55): warning CS0649: Field 'Gen<T>.Fld6' is never assigned to, and will always have its default value // [TypeAttribute(typeof(L1.L2.L3<>.L4<>))] public T Fld6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld6").WithArguments("Gen<T>.Fld6", "").WithLocation(4, 55)); } [WorkItem(543914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543914")] [Fact] public void OpenGenericTypeInAttribute() { var source = @" class Gen<T> {} class Gen2<T>: System.Attribute {} [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, null, options: opt, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,16): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class Gen2<T>: System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 16), // (5,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(6, 2)); } [Fact] public void OpenGenericTypeInAttributeWithGenericAttributeFeature() { var source = @" class Gen<T> {} class Gen2<T> : System.Attribute {} class Gen3<T> : System.Attribute { Gen3(T parameter) { } } [Gen] [Gen2] [Gen2()] [Gen2<U>] [Gen2<System.Collections.Generic.List<U>>] [Gen3(1)] public class Test<U> { public static int Main() { return 1; } }"; CSharpCompilationOptions opt = TestOptions.ReleaseDll; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); compilation.VerifyDiagnostics( // (6,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(6, 2), // (7,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(7, 2), // (8,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2()] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(8, 2), // (9,2): error CS8958: 'U': an attribute type argument cannot use type parameters // [Gen2<U>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<U>").WithArguments("U").WithLocation(9, 2), // (10,2): error CS8958: 'System.Collections.Generic.List<U>': an attribute type argument cannot use type parameters // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Gen2<System.Collections.Generic.List<U>>").WithArguments("System.Collections.Generic.List<U>").WithLocation(10, 2), // (10,2): error CS0579: Duplicate 'Gen2<>' attribute // [Gen2<System.Collections.Generic.List<U>>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Gen2<System.Collections.Generic.List<U>>").WithArguments("Gen2<>").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'Gen3<T>' requires 1 type arguments // [Gen3(1)] Diagnostic(ErrorCode.ERR_BadArity, "Gen3").WithArguments("Gen3<T>", "type", "1").WithLocation(11, 2)); } [Fact] public void GenericAttributeTypeFromILSource() { var ilSource = @" .class public Gen<T> { } .class public Gen2<T> extends [mscorlib] System.Attribute { } "; var csharpSource = @" [Gen] [Gen2] public class Test { public static int Main() { return 1; } }"; var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,2): error CS0616: 'Gen<T>' is not an attribute class // [Gen] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Gen").WithArguments("Gen<T>").WithLocation(2, 2), // (3,2): error CS0305: Using the generic type 'Gen2<T>' requires 1 type arguments // [Gen2] Diagnostic(ErrorCode.ERR_BadArity, "Gen2").WithArguments("Gen2<T>", "type", "1").WithLocation(3, 2)); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void Warnings_Unassigned_Unreferenced_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class B : Attribute { public Type PublicField; // CS0649 private Type PrivateField; // CS0169 protected Type ProtectedField; // CS0649 internal Type InternalField; // CS0649 }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,17): warning CS0649: Field 'B.PublicField' is never assigned to, and will always have its default value null // public Type PublicField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "PublicField").WithArguments("B.PublicField", "null"), // (8,18): warning CS0169: The field 'B.PrivateField' is never used // private Type PrivateField; // CS0169 Diagnostic(ErrorCode.WRN_UnreferencedField, "PrivateField").WithArguments("B.PrivateField"), // (9,20): warning CS0649: Field 'B.ProtectedField' is never assigned to, and will always have its default value null // protected Type ProtectedField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ProtectedField").WithArguments("B.ProtectedField", "null"), // (10,19): warning CS0649: Field 'B.InternalField' is never assigned to, and will always have its default value null // internal Type InternalField; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "InternalField").WithArguments("B.InternalField", "null")); } [WorkItem(544230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544230")] [Fact] public void No_Warnings_For_Assigned_AttributeTypeFields() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class A : Attribute { public Type PublicField; // No CS0649 private Type PrivateField; // No CS0649 protected Type ProtectedField; // No CS0649 internal Type InternalField; // No CS0649 [A(PublicField = typeof(int))] [A(PrivateField = typeof(int))] [A(ProtectedField = typeof(int))] [A(InternalField = typeof(int))] static void Main() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,8): error CS0617: 'PrivateField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(PrivateField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "PrivateField").WithArguments("PrivateField"), // (14,8): error CS0617: 'ProtectedField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(ProtectedField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "ProtectedField").WithArguments("ProtectedField"), // (15,8): error CS0617: 'InternalField' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. // [A(InternalField = typeof(int))] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgument, "InternalField").WithArguments("InternalField")); } [WorkItem(544351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544351")] [Fact] public void CS0182_ERR_BadAttributeArgument_Bug_12638() { var source = @" using System; [A(X = new Array[] { new[] { 1 } })] class A : Attribute { public object X; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,8): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = new Array[] { new[] { 1 } })] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "new Array[] { new[] { 1 } }").WithLocation(4, 8)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions() { var source = @"using System; [A((int)(object)""ABC"")] class A : Attribute { public A(int x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((int)(object)"ABC")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(int)(object)""ABC""").WithLocation(3, 4)); } [WorkItem(544348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544348")] [Fact] public void CS0182_ERR_BadAttributeArgument_WithConversions_02() { var source = @"using System; [A((object[])(object)( new [] { 1 }))] class A : Attribute { public A(object[] x) { } } [B((object[])(object)(new string[] { ""a"", null }))] class B : Attribute { public B(object[] x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (3,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A((object[])(object)( new [] { 1 }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "(object[])(object)( new [] { 1 })").WithLocation(3, 4), // (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [B((object[])(object)(new string[] { "a", null }))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"(object[])(object)(new string[] { ""a"", null })").WithLocation(9, 4)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue() { // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. var source = @" using System; class A : Attribute { public object X; } class C<T> { [A(X = C<T>.E.V)] public enum E { V } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(X = C<T>.E.V)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C<T>.E.V").WithLocation(11, 12)); } [WorkItem(529392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529392")] [Fact] public void AttributeArgument_ConstructedType_ConstantValue() { // See comments for test CS0182_ERR_BadAttributeArgument_OpenType_ConstantValue var source = @" using System; class A : Attribute { public object X; public static void Main() { typeof(C<>.E).GetCustomAttributes(false); } } public class C<T> { [A(X = C<int>.E.V)] public enum E { V } }"; CompileAndVerify(source, expectedOutput: ""); } [WorkItem(544512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544512")] [Fact] public void LambdaInAttributeArg() { string source = @" public delegate void D(); public class myAttr : System.Attribute { public D d { get { return () => { }; } set { } } } [myAttr(d = () => { })] class X { public static int Main() { return 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): error CS0655: 'd' is not a valid named attribute argument because it is not a valid attribute parameter type // [myAttr(d = () => { })] Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "d").WithArguments("d").WithLocation(14, 9)); } [WorkItem(544590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544590")] [Fact] public void LambdaInAttributeArg2() { string source = @" using System; [AttributeUsage(AttributeTargets.All)] public class Goo : Attribute { public Goo(int sName) { } } public class Class1 { [field: Goo(((System.Func<int>)(() => 5))())] public event EventHandler Click; public static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [field: Goo(((System.Func<int>)(() => 5))())] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "((System.Func<int>)(() => 5))()"), // (12,31): warning CS0067: The event 'Class1.Click' is never used // public event EventHandler Click; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("Class1.Click")); } [WorkItem(545030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545030")] [Fact] public void UserDefinedAttribute_Bug13264() { string source = @" namespace System.Runtime.InteropServices { [DllImport] // Error class DllImportAttribute {} } namespace System { [Object] // Warning public class Object : System.Attribute {} } "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,6): error CS0616: 'System.Runtime.InteropServices.DllImportAttribute' is not an attribute class // [DllImport] // Error Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "DllImport").WithArguments("System.Runtime.InteropServices.DllImportAttribute"), // (9,6): warning CS0436: The type 'System.Object' in '' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // [Object] // Warning Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object")); } [WorkItem(545241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545241")] [Fact] public void ConditionalAttributeOnAttribute() { string source = @" using System; using System.Diagnostics; [Conditional(""A"")] class Attr1 : Attribute { } class Attr2 : Attribute { } class Attr3 : Attr1 { } [Attr1, Attr2, Attr3] class Test { } "; Action<ModuleSymbol> sourceValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(3, attrs.Length); }; Action<ModuleSymbol> metadataValidator = module => { var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var attrs = type.GetAttributes(); Assert.Equal(1, attrs.Length); // only one is not conditional Assert.Equal("Attr2", attrs.Single().AttributeClass.Name); }; CompileAndVerify(source, sourceSymbolValidator: sourceValidator, symbolValidator: metadataValidator); } [WorkItem(545499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545499")] [Fact] public void IncompleteMethodParamAttribute() { string source = @" using System; public class MyAttribute2 : Attribute { public Type[] Types; } public class Test { public void goo([MyAttribute2(Types = new Type[ "; var compilation = CreateCompilation(source); Assert.NotEmpty(compilation.GetDiagnostics()); } [Fact, WorkItem(545556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545556")] public void NameLookupInDelegateParameterAttribute() { var source = @" using System; class A : Attribute { new const int Equals = 1; delegate void F([A(Equals)] int x); public A(int x) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS1503: Argument 1: cannot convert from 'method group' to 'int' // delegate void F([A(Equals)] int x); Diagnostic(ErrorCode.ERR_BadArgType, "Equals").WithArguments("1", "method group", "int")); } [Fact, WorkItem(546234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546234")] public void AmbiguousClassNamespaceLookup() { // One from source, one from PE var source = @" using System; [System] class System : Attribute { } "; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"), // (2,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'System' is a type not a namespace. Consider a 'using static' directive instead // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System").WithLocation(2, 7), // (4,16): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // class System : Attribute Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute"), // (3,2): error CS0616: 'System' is not an attribute class // [System] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); source = @" [assembly: X] namespace X { } "; var source2 = @" using System; public class X: Attribute { } "; var comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp0").ToMetadataReference(); CreateCompilationWithMscorlib40(source, references: new[] { comp1 }).VerifyDiagnostics( // (2,12): error CS0616: 'X' is not an attribute class // [assembly: X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, none from Source source2 = @" using System; public class X { } "; var source3 = @" namespace X { } "; var source4 = @" [X] class Y { } "; comp1 = CreateCompilationWithMscorlib40(source2, assemblyName: "Temp1").ToMetadataReference(); var comp2 = CreateEmptyCompilation(source3, assemblyName: "Temp2").ToMetadataReference(); var comp3 = CreateCompilationWithMscorlib40(source4, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0434: The namespace 'X' in 'Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with the type 'X' in 'Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // [X] Diagnostic(ErrorCode.ERR_SameFullNameNsAgg, "X").WithArguments("Temp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X", "Temp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "X")); // Multiple from PE, one from Source: Failure var source5 = @" [X] class X { } "; comp3 = CreateCompilationWithMscorlib40(source5, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (2,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); // Multiple from PE, one from Source: Success source5 = @" using System; [X] class X: Attribute { } "; CompileAndVerifyWithMscorlib40(source5, references: new[] { comp1, comp2 }); // Multiple from PE, multiple from Source var source6 = @" [X] class X { } namespace X { } "; comp3 = CreateCompilationWithMscorlib40(source6, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (3,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'X' // class X Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "X").WithArguments("X", "<global namespace>")); // Multiple from PE, one from Source with alias var source7 = @" using System; using X = Goo; [X] class Goo: Attribute { } "; comp3 = CreateCompilationWithMscorlib40(source7, references: new[] { comp1, comp2 }); comp3.VerifyDiagnostics( // (4,2): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'X' // [X] Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "X").WithArguments("X", "<global namespace>"), // (4,2): error CS0616: 'X' is not an attribute class // [X] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "X").WithArguments("X")); } [Fact] public void AmbiguousClassNamespaceLookup_Container() { var source1 = @"using System; public class A : Attribute { } namespace N1 { public class B : Attribute { } public class C : Attribute { } }"; var comp = CreateCompilation(source1, assemblyName: "A"); var ref1 = comp.EmitToImageReference(); var source2 = @"using System; using N1; using N2; namespace N1 { class A : Attribute { } class B : Attribute { } } namespace N2 { class C : Attribute { } } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }, assemblyName: "B"); comp.VerifyDiagnostics( // (14,2): warning CS0436: The type 'B' in '' conflicts with the imported type 'B' in 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // [B] Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "B").WithArguments("", "N1.B", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N1.B").WithLocation(14, 2), // (15,2): error CS0104: 'C' is an ambiguous reference between 'N2.C' and 'N1.C' // [C] Diagnostic(ErrorCode.ERR_AmbigContext, "C").WithArguments("C", "N2.C", "N1.C").WithLocation(15, 2)); } [Fact] public void AmbiguousClassNamespaceLookup_Generic() { var source1 = @"public class A { } public class B<T> { } public class C<T, U> { }"; var comp = CreateCompilation(source1); var ref1 = comp.EmitToImageReference(); var source2 = @"class A<U> { } class B<U> { } class C<U> { } [A] [B] [C] class D { }"; comp = CreateCompilation(source2, references: new[] { ref1 }); comp.VerifyDiagnostics( // (4,2): error CS0616: 'A' is not an attribute class // [A] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "A").WithArguments("A").WithLocation(4, 2), // (5,2): error CS0616: 'B<U>' is not an attribute class // [B] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "B").WithArguments("B<U>").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'C<U>' requires 1 type arguments // [C] Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<U>", "type", "1").WithLocation(6, 2)); } [WorkItem(546283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546283")] [Fact] public void ApplyIndexerNameAttributeTwice() { var source = @"using System.Runtime.CompilerServices; public class IA { [IndexerName(""ItemX"")] [IndexerName(""ItemY"")] public virtual int this[int index] { get { return 1;} set {} } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,3): error CS0579: Duplicate 'IndexerName' attribute // [IndexerName("ItemY")] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "IndexerName").WithArguments("IndexerName").WithLocation(6, 3)); var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("IA").GetMember<PropertySymbol>(WellKnownMemberNames.Indexer); Assert.Equal("ItemX", indexer.MetadataName); //First one wins. } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute1() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute2() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); // we now recognize the extension method even without the assembly-level attribute var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.True(method.TestIsExtensionBitTrue); Assert.True(method.IsExtensionMethod); } [WorkItem(530524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530524")] [Fact] public void PEMethodSymbolExtensionAttribute3() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly '<<GeneratedFileName>>' { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) } .class public E { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(object o) { ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void M(object o) { o.M(); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics( // (5,11): error CS1061: 'object' does not contain a definition for 'M' and no extension method 'M' accepting a // first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) // o.M(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("object", "M")); var assembly = compilation.Assembly; Assert.Equal(0, assembly.GetAttributes().Length); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E"); Assert.Equal(0, type.GetAttributes().Length); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); Assert.True(method.TestIsExtensionBitSet); Assert.False(method.TestIsExtensionBitTrue); Assert.False(method.IsExtensionMethod); } [WorkItem(530310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530310")] [Fact] public void PEParameterSymbolParamArrayAttribute() { var source1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }"; var reference1 = CompileIL(source1, prependDefaultHeader: false); var source2 = @"class C { static void Main(string[] args) { A.M(1, 2, 3); A.M(1, 2, 3, 4); } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); compilation.VerifyDiagnostics(); var method = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<PEMethodSymbol>("M"); Assert.Equal(0, method.GetAttributes().Length); var yParam = method.Parameters[1]; Assert.True(yParam.IsParams); Assert.Equal(0, yParam.GetAttributes().Length); } [WorkItem(546490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546490")] [Fact] public void Bug15984() { var source1 = @" .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Goo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Goo::inc } // end of class Library1.Goo "; var reference1 = CompileIL(source1, prependDefaultHeader: false); var compilation = CreateCompilation("", new[] { reference1 }); var type = compilation.GetTypeByMetadataName("Library1.Goo"); Assert.Equal(0, type.GetAttributes()[0].ConstructorArguments.Count()); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void GenericAttributeType() { var source = @" using System; [A<>] // 1, 2 [A<int>] // 3, 4 [B] // 5 [B<>] // 6, 7 [B<int>] // 8, 9 [C] // 10 [C<>] // 11, 12 [C<int>] // 13, 14 [C<,>] // 15, 16 [C<int, int>] // 17, 18 class Test { } public class A : Attribute { } public class B<T> : Attribute // 19 { } public class C<T, U> : Attribute // 20 { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<>").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<>").WithArguments("generic attributes").WithLocation(7, 2), // (8,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_FeatureInPreview, "B<int>").WithArguments("generic attributes").WithLocation(8, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (10,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (11,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int>").WithArguments("generic attributes").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (12,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<,>").WithArguments("generic attributes").WithLocation(12, 2), // (13,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<int, int>").WithArguments("generic attributes").WithLocation(13, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2), // (22,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class B<T> : Attribute // 19 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(22, 21), // (26,24): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T, U> : Attribute // 20 Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(26, 24)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<>] // 1, 2 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<>").WithArguments("A", "type").WithLocation(4, 2), // (5,2): error CS0308: The non-generic type 'A' cannot be used with type arguments // [A<int>] // 3, 4 Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type").WithLocation(5, 2), // (6,2): error CS0305: Using the generic type 'B<T>' requires 1 type arguments // [B] // 5 Diagnostic(ErrorCode.ERR_BadArity, "B").WithArguments("B<T>", "type", "1").WithLocation(6, 2), // (7,2): error CS7003: Unexpected use of an unbound generic name // [B<>] // 6, 7 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "B<>").WithLocation(7, 2), // (8,2): error CS0579: Duplicate 'B<>' attribute // [B<int>] // 8, 9 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "B<int>").WithArguments("B<>").WithLocation(8, 2), // (9,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C] // 10 Diagnostic(ErrorCode.ERR_BadArity, "C").WithArguments("C<T, U>", "type", "2").WithLocation(9, 2), // (10,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<>] // 11, 12 Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T, U>", "type", "2").WithLocation(10, 2), // (11,2): error CS0305: Using the generic type 'C<T, U>' requires 2 type arguments // [C<int>] // 13, 14 Diagnostic(ErrorCode.ERR_BadArity, "C<int>").WithArguments("C<T, U>", "type", "2").WithLocation(11, 2), // (12,2): error CS7003: Unexpected use of an unbound generic name // [C<,>] // 15, 16 Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<,>").WithLocation(12, 2), // (13,2): error CS0579: Duplicate 'C<,>' attribute // [C<int, int>] // 17, 18 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<int, int>").WithArguments("C<,>").WithLocation(13, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Source() { var source = @" using System; using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } public class C<T> : Attribute { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "Attribute").WithArguments("generic attributes").WithLocation(12, 21), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(6, 2), // (7,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(7, 2)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (7,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(7, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Metadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using Alias = C<int>; [Alias] [Alias<>] [Alias<int>] class Test { } "; // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. var comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias").WithArguments("generic attributes").WithLocation(4, 2), // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [Alias<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "Alias<int>").WithArguments("generic attributes").WithLocation(6, 2)); // NOTE: Dev11 does not give an error for "[Alias]" - it just silently drops the // attribute at emit-time. comp = CreateCompilationWithILAndMscorlib40(source, il, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<>").WithArguments("Alias", "using alias").WithLocation(5, 2), // (6,2): error CS0307: The using alias 'Alias' cannot be used with type arguments // [Alias<int>] Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Alias<int>").WithArguments("Alias", "using alias").WithLocation(6, 2)); } [WorkItem(611177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611177")] [Fact] public void AliasedGenericAttributeType_Nested() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [InnerAlias] Diagnostic(ErrorCode.ERR_FeatureInPreview, "InnerAlias").WithArguments("generic attributes").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17), // (8,6): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_FeatureInPreview, "OuterAlias.Inner").WithArguments("generic attributes").WithLocation(8, 6)); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS0616: 'Outer<int>.Inner' is not an attribute class // [InnerAlias] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "InnerAlias").WithArguments("Outer<int>.Inner").WithLocation(5, 2), // (8,17): error CS0616: 'Outer<int>.Inner' is not an attribute class // [OuterAlias.Inner] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Inner").WithArguments("Outer<int>.Inner").WithLocation(8, 17)); } [Fact] public void NestedWithGenericAttributeFeature() { var source = @" [Outer<int>.Inner] class Test { [Outer<int>.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [Fact] public void AliasedGenericAttributeType_NestedWithGenericAttributeFeature_IsAttribute() { var source = @" using InnerAlias = Outer<int>.Inner; using OuterAlias = Outer<int>; [InnerAlias] class Test { [OuterAlias.Inner] static void Main() { } } public class Outer<T> { public class Inner : System.Attribute { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void VerbatimAliasVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using ActionAttribute = A.ActionAttribute; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(687816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687816")] [Fact] public void DeclarationVersusNonVerbatimAlias() { var source = @" using Action = A.ActionAttribute; using A; namespace A { class ActionAttribute : System.Attribute { } } class Program { [Action] static void Main(string[] args) { } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS1614: 'Action' is ambiguous between 'A.ActionAttribute' and 'A.ActionAttribute'; use either '@Action' or 'ActionAttribute' // [Action] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "Action").WithArguments("Action", "A.ActionAttribute", "A.ActionAttribute")); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasNewLineDependency)] public void Repro728865() { var source = @" using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Microsoft.Yeti; namespace PFxIntegration { public class ProducerConsumerScenario { static void Main(string[] args) { Type program = typeof(ProducerConsumerScenario); MethodInfo methodInfo = program.GetMethod(""ProducerConsumer""); Object[] myAttributes = methodInfo.GetCustomAttributes(false); ; if (myAttributes.Length > 0) { Console.WriteLine(""\r\nThe attributes for the method - {0} - are: \r\n"", methodInfo); for (int j = 0; j < myAttributes.Length; j++) Console.WriteLine(""The type of the attribute is {0}"", myAttributes[j]); } } public enum CollectionType { Default, Queue, Stack, Bag } public ProducerConsumerScenario() { } [CartesianRowData( new int[] { 5, 100, 100000 }, new CollectionType[] { CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag })] public void ProducerConsumer(int inputSize, CollectionType collectionType) { Console.WriteLine(""Hello""); } } } namespace Microsoft.Yeti { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class CartesianRowDataAttribute : Attribute { public CartesianRowDataAttribute() { } public CartesianRowDataAttribute(params object[] data) { IEnumerable<object>[] asEnum = new IEnumerable<object>[data.Length]; for (int i = 0; i < data.Length; ++i) { WrapEnum((IEnumerable)data[i]); } } static void WrapEnum(IEnumerable x) { foreach (object a in x) { Console.WriteLine("" - "" + a + "" -""); } } } // class } // namespace "; CompileAndVerify(source, expectedOutput: @" - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer(Int32, CollectionType) - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute "); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument1() { var source = @" using System; public class Test { [ArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument2() { var source = @" using System; public class Test { [ParamArrayOnlyAttribute(new string[] { ""A"" })] //error [ObjectOnlyAttribute(new string[] { ""A"" })] [ParamArrayOrObjectAttribute(new string[] { ""A"" })] //error, even though the object ctor would work void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { ""A"" })] [ObjectOnlyAttribute(new object[] { ""A"" })] [ParamArrayOrObjectAttribute(new object[] { ""A"" })] //array void M3() { } [ParamArrayOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [ParamArrayOrObjectAttribute(""A"")] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOnlyAttribute(new string[] { ""A"" })"), // (8,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ParamArrayOrObjectAttribute(new string[] { "A" })] //error, even though the object ctor would work Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ParamArrayOrObjectAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { "A" }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, "A"); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, "A"); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void StringArrayArgument3() { var source = @" using System; public class Test { [StringOnlyAttribute(new string[] { ""A"" })] [ObjectOnlyAttribute(new string[] { ""A"" })] //error [StringOrObjectAttribute(new string[] { ""A"" })] //string void M1() { } [StringOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [StringOrObjectAttribute(null)] //string void M2() { } //[StringOnlyAttribute(new object[] { ""A"" })] //overload resolution failure [ObjectOnlyAttribute(new object[] { ""A"" })] [StringOrObjectAttribute(new object[] { ""A"" })] //object void M3() { } [StringOnlyAttribute(""A"")] [ObjectOnlyAttribute(""A"")] [StringOrObjectAttribute(""A"")] //string void M4() { } } public class StringOnlyAttribute : Attribute { public StringOnlyAttribute(params string[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class StringOrObjectAttribute : Attribute { public StringOrObjectAttribute(params string[] array) { } public StringOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [ObjectOnlyAttribute(new string[] { "A" })] //error Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"ObjectOnlyAttribute(new string[] { ""A"" })")); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new string[] { "A" }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (string[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { "A" }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { "A" }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument1() { var source = @" using System; public class Test { //[ArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ArrayOrObjectAttribute(null)] //array void M2() { } [ArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } } public class ArrayOnlyAttribute : Attribute { public ArrayOnlyAttribute(object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ArrayOrObjectAttribute : Attribute { public ArrayOrObjectAttribute(object[] array) { } public ArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument2() { var source = @" using System; public class Test { //[ParamArrayOnlyAttribute(new int[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new int[] { 1 })] [ParamArrayOrObjectAttribute(new int[] { 1 })] //object void M1() { } [ParamArrayOnlyAttribute(null)] [ObjectOnlyAttribute(null)] [ParamArrayOrObjectAttribute(null)] //array void M2() { } [ParamArrayOnlyAttribute(new object[] { 1 })] [ObjectOnlyAttribute(new object[] { 1 })] [ParamArrayOrObjectAttribute(new object[] { 1 })] //array void M3() { } [ParamArrayOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [ParamArrayOrObjectAttribute(1)] //object void M4() { } } public class ParamArrayOnlyAttribute : Attribute { public ParamArrayOnlyAttribute(params object[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(object o) { } } public class ParamArrayOrObjectAttribute : Attribute { public ParamArrayOrObjectAttribute(params object[] array) { } public ParamArrayOrObjectAttribute(object o) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); // As in the test above (i.e. not affected by params modifier). var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, value1); // As in the test above (i.e. not affected by params modifier). var attrs2 = method2.GetAttributes(); attrs2[0].VerifyValue(0, TypedConstantKind.Array, (object[])null); attrs2[1].VerifyValue(0, TypedConstantKind.Primitive, (object)null); attrs2[2].VerifyValue(0, TypedConstantKind.Array, (object[])null); // As in the test above (i.e. not affected by params modifier). var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[2].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); attrs4[0].VerifyValue(0, TypedConstantKind.Array, new object[] { 1 }); attrs4[1].VerifyValue(0, TypedConstantKind.Primitive, 1); attrs4[2].VerifyValue(0, TypedConstantKind.Primitive, 1); } [WorkItem(728865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728865")] [Fact] public void IntArrayArgument3() { var source = @" using System; public class Test { [IntOnlyAttribute(new int[] { 1 })] [ObjectOnlyAttribute(new int[] { 1 })] [IntOrObjectAttribute(new int[] { 1 })] //int void M1() { } [IntOnlyAttribute(null)] [ObjectOnlyAttribute(null)] //[IntOrObjectAttribute(null)] //ambiguous void M2() { } //[IntOnlyAttribute(new object[] { 1 })] //overload resolution failure [ObjectOnlyAttribute(new object[] { 1 })] [IntOrObjectAttribute(new object[] { 1 })] //object void M3() { } [IntOnlyAttribute(1)] [ObjectOnlyAttribute(1)] [IntOrObjectAttribute(1)] //int void M4() { } } public class IntOnlyAttribute : Attribute { public IntOnlyAttribute(params int[] array) { } } public class ObjectOnlyAttribute : Attribute { public ObjectOnlyAttribute(params object[] array) { } } public class IntOrObjectAttribute : Attribute { public IntOrObjectAttribute(params int[] array) { } public IntOrObjectAttribute(params object[] array) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var method1 = type.GetMember<MethodSymbol>("M1"); var method2 = type.GetMember<MethodSymbol>("M2"); var method3 = type.GetMember<MethodSymbol>("M3"); var method4 = type.GetMember<MethodSymbol>("M4"); var attrs1 = method1.GetAttributes(); var value1 = new int[] { 1 }; attrs1[0].VerifyValue(0, TypedConstantKind.Array, value1); attrs1[1].VerifyValue(0, TypedConstantKind.Array, new object[] { value1 }); attrs1[2].VerifyValue(0, TypedConstantKind.Array, value1); var attrs2 = method2.GetAttributes(); var value2 = (object[])null; attrs2[0].VerifyValue(0, TypedConstantKind.Array, value2); attrs2[1].VerifyValue(0, TypedConstantKind.Array, value2); var attrs3 = method3.GetAttributes(); var value3 = new object[] { 1 }; attrs3[0].VerifyValue(0, TypedConstantKind.Array, value3); attrs3[1].VerifyValue(0, TypedConstantKind.Array, value3); var attrs4 = method4.GetAttributes(); var value4 = new object[] { 1 }; attrs4[0].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[1].VerifyValue(0, TypedConstantKind.Array, value4); attrs4[2].VerifyValue(0, TypedConstantKind.Array, value4); } [WorkItem(739630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739630")] [Fact] public void NullVersusEmptyArray() { var source = @" using System; public class ArrayAttribute : Attribute { public int[] field; public ArrayAttribute(int[] param) { } } public class Test { [Array(null)] void M0() { } [Array(new int[] { })] void M1() { } [Array(null, field=null)] void M2() { } [Array(new int[] { }, field = null)] void M3() { } [Array(null, field = new int[] { })] void M4() { } [Array(new int[] { }, field = new int[] { })] void M5() { } static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var methods = Enumerable.Range(0, 6).Select(i => type.GetMember<MethodSymbol>("M" + i)); var attrs = methods.Select(m => m.GetAttributes().Single()).ToArray(); var nullArray = (int[])null; var emptyArray = new int[0]; const string fieldName = "field"; attrs[0].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[1].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[2].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[2].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[3].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[3].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray); attrs[4].VerifyValue(0, TypedConstantKind.Array, nullArray); attrs[4].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); attrs[5].VerifyValue(0, TypedConstantKind.Array, emptyArray); attrs[5].VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray); } [Fact] [WorkItem(530266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530266")] public void UnboundGenericTypeInTypedConstant() { var source = @" using System; public class TestAttribute : Attribute { public TestAttribute(Type x){} } [TestAttribute(typeof(Target<>))] class Target<T> {}"; var comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); var typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); var comp2 = CreateCompilation("", new[] { comp.EmitToImageReference() }); type = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Target"); Assert.IsAssignableFrom<PENamedTypeSymbol>(type); typeInAttribute = (INamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().Value; Assert.True(typeInAttribute.IsUnboundGenericType); Assert.True(((NamedTypeSymbol)type.GetAttributes()[0].ConstructorArguments.First().ValueInternal).IsUnboundGenericType); Assert.Equal("Target<>", typeInAttribute.ToTestDisplayString()); } [Fact, WorkItem(1020038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020038")] public void Bug1020038() { var source1 = @" public class CTest {} "; var compilation1 = CreateCompilation(source1, assemblyName: "Bug1020038"); var source2 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(CTest))] class Test {} "; var compilation2 = CreateCompilation(source2, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation2, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); var source3 = @" class CAttr : System.Attribute { public CAttr(System.Type x){} } [CAttr(typeof(System.Func<System.Action<CTest>>))] class Test {} "; var compilation3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(compilation1) }); CompileAndVerify(compilation3, symbolValidator: (m) => { Assert.Equal(2, m.ReferencedAssemblies.Length); Assert.Equal("Bug1020038", m.ReferencedAssemblies[1].Name); }); } [Fact, WorkItem(937575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937575"), WorkItem(121, "CodePlex")] public void Bug937575() { var source = @" using System; class XAttribute : Attribute { } class C<T> { public void M<[X]U>() { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(compilation, symbolValidator: (m) => { var cc = m.GlobalNamespace.GetTypeMember("C"); var mm = cc.GetMember<MethodSymbol>("M"); Assert.True(cc.TypeParameters.Single().GetAttributes().IsEmpty); Assert.Equal("XAttribute", mm.TypeParameters.Single().GetAttributes().Single().ToString()); }); } [WorkItem(1144603, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1144603")] [Fact] public void EmitMetadataOnlyInPresenceOfErrors() { var source1 = @" public sealed class DiagnosticAnalyzerAttribute : System.Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public static class LanguageNames { public const xyz CSharp = ""C#""; } "; var compilation1 = CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll); compilation1.VerifyDiagnostics( // (10,18): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // public const xyz CSharp = "C#"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "xyz").WithArguments("xyz").WithLocation(10, 18)); var source2 = @" [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpCompilerDiagnosticAnalyzer {} "; var compilation2 = CreateCompilationWithMscorlib40(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll, assemblyName: "Test.dll"); Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols[1]); compilation2.VerifyDiagnostics(); var emitResult2 = compilation2.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult2.Success); emitResult2.Diagnostics.Verify( // error CS7038: Failed to emit module 'Test.dll': Module has invalid attributes. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("Test.dll", "Module has invalid attributes.").WithLocation(1, 1)); // Use different mscorlib to test retargeting scenario var compilation3 = CreateCompilationWithMscorlib45(source2, new[] { new CSharpCompilationReference(compilation1) }, options: TestOptions.DebugDll); Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols[1]); compilation3.VerifyDiagnostics( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); var emitResult3 = compilation3.Emit(peStream: new MemoryStream(), options: new EmitOptions(metadataOnly: true)); Assert.False(emitResult3.Success); emitResult3.Diagnostics.Verify( // (2,35): error CS0246: The type or namespace name 'xyz' could not be found (are you missing a using directive or an assembly reference?) // [DiagnosticAnalyzer(LanguageNames.CSharp)] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CSharp").WithArguments("xyz").WithLocation(2, 35)); } [Fact, WorkItem(30833, "https://github.com/dotnet/roslyn/issues/30833")] public void AttributeWithTaskDelegateParameter() { string code = @" using System; using System.Threading.Tasks; namespace a { class Class1 { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class CommandAttribute : Attribute { public delegate Task FxCommand(); public CommandAttribute(FxCommand Fx) { this.Fx = Fx; } public FxCommand Fx { get; set; } } [Command(UserInfo)] public static async Task UserInfo() { await Task.CompletedTask; } } } "; CreateCompilationWithMscorlib46(code).VerifyDiagnostics( // (22,4): error CS0181: Attribute constructor parameter 'Fx' has type 'Class1.CommandAttribute.FxCommand', which is not a valid attribute parameter type // [Command(UserInfo)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Command").WithArguments("Fx", "a.Class1.CommandAttribute.FxCommand").WithLocation(22, 4)); } [Fact, WorkItem(33388, "https://github.com/dotnet/roslyn/issues/33388")] public void AttributeCrashRepro_33388() { string source = @" using System; public static class C { public static int M(object obj) => 42; public static int M(C2 c2) => 42; } public class RecAttribute : Attribute { public RecAttribute(int i) { this.i = i; } private int i; } [Rec(C.M(null))] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,6): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Rec(C.M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(null)").WithLocation(20, 6)); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttribute_Delegate() { string source = @" using System; public class C { [Obsolete] public void M() { } void M2() { Action a = M; a = new Action(M); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS0612: 'C.M()' is obsolete // Action a = M; Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(12, 20), // (13,24): warning CS0612: 'C.M()' is obsolete // a = new Action(M); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M").WithArguments("C.M()").WithLocation(13, 24) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void ObsoleteAttributeWithUnsafeError() { string source = @" using System; unsafe delegate byte* D(); class C { [Obsolete(null, true)] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (7,35): warning CS0612: 'C.F()' is obsolete // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "F").WithArguments("C.F()").WithLocation(7, 35), // (8,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(8, 28) ); } [Fact] [WorkItem(47308, "https://github.com/dotnet/roslyn/issues/47308")] public void UnmanagedAttributeWithUnsafeError() { string source = @" using System.Runtime.InteropServices; unsafe delegate byte* D(); class C { [UnmanagedCallersOnly] unsafe static byte* F() => default; unsafe static D M1() => new D(F); static D M2() => new D(F); } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class UnmanagedCallersOnlyAttribute : Attribute { public UnmanagedCallersOnlyAttribute() { } public Type[] CallConvs; public string EntryPoint; } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (8,35): error CS8902: 'C.F()' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method. // unsafe static D M1() => new D(F); Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate, "F").WithArguments("C.F()").WithLocation(8, 35), // (9,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static D M2() => new D(F); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "F").WithLocation(9, 28) ); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage() { var lib_cs = @" public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_2() { var source = @" class A<T> : System.Attribute {} class A : System.Attribute {} [A] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 14) ); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_3() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_4() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class A : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void VerifyGenericAttributeExistenceDoesNotAffectBindingOfNonGenericUsage_5() { var lib_cs = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} public class AAttribute : System.Attribute {} "; var source = @" [A] public class C { }"; var libRef = CreateCompilation(lib_cs, parseOptions: TestOptions.RegularPreview).EmitToImageReference(); var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, references: new[] { libRef }); comp.VerifyDiagnostics(); Assert.False(comp.GlobalNamespace.GetTypeMember("C").GetAttributes().Single().AttributeClass.IsGenericType); } [Fact] public void MetadataForUsingGenericAttribute() { var source = @" public class A<T> : System.Attribute {} public class C { [A<int>] public void M() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); static void validate(ModuleSymbol module) { var m = (MethodSymbol)module.ContainingAssembly.GlobalNamespace.GetMember("C.M"); var attribute = m.GetAttributes().Single(); Assert.Equal("A<System.Int32>", attribute.AttributeClass.ToTestDisplayString()); Assert.Equal("A<System.Int32>..ctor()", attribute.AttributeConstructor.ToTestDisplayString()); } } [Fact] public void AmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [A<int>] public class C { }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "A<int>").WithArguments("generic attributes").WithLocation(5, 2)); } [Fact, WorkItem(54772, "https://github.com/dotnet/roslyn/issues/54772")] public void ResolveAmbiguityWithGenericAttribute() { var source = @" public class AAttribute<T> : System.Attribute {} public class A<T> : System.Attribute {} [@A<int>] [AAttribute<int>] public class C { }"; // This behavior is incorrect. No ambiguity errors should be reported in the above program. var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,30): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class AAttribute<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 30), // (3,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class A<T> : System.Attribute {} Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(3, 21), // (5,2): error CS1614: 'A<>' is ambiguous between 'A<T>' and 'AAttribute<T>'. Either use '@A<>' or explicitly include the 'Attribute' suffix. // [@A<int>] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "@A<int>").WithArguments("A<>", "A<T>", "AAttribute<T>").WithLocation(5, 2), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [@A<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "@A<int>").WithArguments("generic attributes").WithLocation(5, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [AAttribute<int>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "AAttribute<int>").WithArguments("generic attributes").WithLocation(6, 2)); } [Fact] public void InheritGenericAttribute() { var source1 = @" public class C<T> : System.Attribute { } public class D : C<int> { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void InheritGenericAttributeInMetadata() { var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D extends class C`1<int32> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class C`1<int32>::.ctor() ret } } "; var source = @" [D] public class Program { } "; // Note that this behavior predates the "generic attributes" feature in C# 10. // If a type deriving from a generic attribute is found in metadata, it's permitted to be used as an attribute in C# 9 and below. var comp = CreateCompilationWithIL(source, il, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); comp = CreateCompilationWithIL(source, il); comp.VerifyDiagnostics(); } [Fact] public void InheritAttribute_BaseInsideGeneric() { var source1 = @" public class C<T> { public class Inner : System.Attribute { } } public class D : C<int>.Inner { } "; var source2 = @" [D] public class Program { } "; var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,26): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class Inner : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(4, 26)); var comp1 = CreateCompilation(source1); var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); comp2 = CreateCompilation(source2, references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics(); } [Fact] public void GenericAttribute_Constraints() { var source = @" public class C<T> : System.Attribute where T : struct { } [C<object>] // 1 public class C1 { } [C<int>] public class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C<T>' // [C<object>] // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "object").WithArguments("C<T>", "T", "object").WithLocation(4, 4)); } [Fact] public void GenericAttribute_ErrorTypeArg() { var source = @" public class C<T> : System.Attribute { } [C<ERROR>] [C<System>] [C<>] public class Program { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,21): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public class C<T> : System.Attribute { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(2, 21), // (4,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<ERROR>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<ERROR>").WithArguments("generic attributes").WithLocation(4, 2), // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<System>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<System>").WithArguments("generic attributes").WithLocation(5, 2), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // [C<>] Diagnostic(ErrorCode.ERR_FeatureInPreview, "C<>").WithArguments("generic attributes").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,4): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // [C<ERROR>] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(4, 4), // (5,2): error CS0579: Duplicate 'C<>' attribute // [C<System>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<System>").WithArguments("C<>").WithLocation(5, 2), // (5,4): error CS0118: 'System' is a namespace but is used like a type // [C<System>] Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "type").WithLocation(5, 4), // (6,2): error CS7003: Unexpected use of an unbound generic name // [C<>] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>").WithLocation(6, 2), // (6,2): error CS0579: Duplicate 'C<>' attribute // [C<>] Diagnostic(ErrorCode.ERR_DuplicateAttribute, "C<>").WithArguments("C<>").WithLocation(6, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_Reflection_CoreClr() { var source = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class Program { public static void Main() { var attr = Attribute.GetCustomAttribute(typeof(Program), typeof(Attr<int>)); Console.Write(attr); } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_False() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] // 1 [Attr<int>] // 2 public class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<object>] // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<object>").WithArguments("Attr<>").WithLocation(8, 2), // (9,2): error CS0579: Duplicate 'Attr<>' attribute // [Attr<int>] // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "Attr<int>").WithArguments("Attr<>").WithLocation(9, 2)); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttribute_AllowMultiple_True() { var source = @" using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } [Attr<int>] [Attr<object>] [Attr<int>] public class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "Attr`1[System.Int32] Attr`1[System.Object] Attr`1[System.Int32]"); verifier.VerifyDiagnostics(); } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeInvalidMultipleFromMetadata() { // This IL includes an attribute with `AllowMultiple = false` (the default). // Then the class `D` includes two copies of the attribute. var il = @" .class public auto ansi beforefieldinit C`1<T> extends [mscorlib]System.Attribute { // [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 ff 7f 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } .class public auto ansi beforefieldinit D { .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .custom instance void class C`1<int32>::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } } "; var source = @" using System; class Program { static void Main() { var attrs = Attribute.GetCustomAttributes(typeof(D)); foreach (var attr in attrs) { Console.Write(attr); Console.Write(' '); } } } "; var comp = CreateCompilationWithIL(source, il, options: TestOptions.DebugExe); var verifier = CompileAndVerify( comp, expectedOutput: "C`1[System.Int32] C`1[System.Int32]"); verifier.VerifyDiagnostics(); } [Fact] [WorkItem(54778, "https://github.com/dotnet/roslyn/issues/54778")] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void GenericAttribute_AttributeDependentTypes() { var source = @" #nullable enable using System; using System.Collections.Generic; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr<T> : Attribute { } [Attr<dynamic>] // 1 [Attr<List<dynamic>>] // 2 [Attr<nint>] // 3 [Attr<List<nint>>] // 4 [Attr<string?>] // 5 [Attr<List<string?>>] // 6 [Attr<(int a, int b)>] // 7 [Attr<List<(int a, int b)>>] // 8 [Attr<(int a, string? b)>] // 9 [Attr<ValueTuple<int, int>>] // ok class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS8960: Type 'dynamic' cannot be used in this context because it cannot be represented in metadata. // [Attr<dynamic>] // 1 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<dynamic>").WithArguments("dynamic").WithLocation(10, 2), // (11,2): error CS8960: Type 'List<dynamic>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<dynamic>>] // 2 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<dynamic>>").WithArguments("List<dynamic>").WithLocation(11, 2), // (12,2): error CS8960: Type 'nint' cannot be used in this context because it cannot be represented in metadata. // [Attr<nint>] // 3 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<nint>").WithArguments("nint").WithLocation(12, 2), // (13,2): error CS8960: Type 'List<nint>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<nint>>] // 4 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<nint>>").WithArguments("List<nint>").WithLocation(13, 2), // (14,2): error CS8960: Type 'string?' cannot be used in this context because it cannot be represented in metadata. // [Attr<string?>] // 5 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<string?>").WithArguments("string?").WithLocation(14, 2), // (15,2): error CS8960: Type 'List<string?>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<string?>>] // 6 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<string?>>").WithArguments("List<string?>").WithLocation(15, 2), // (16,2): error CS8960: Type '(int a, int b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, int b)>] // 7 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, int b)>").WithArguments("(int a, int b)").WithLocation(16, 2), // (17,2): error CS8960: Type 'List<(int a, int b)>' cannot be used in this context because it cannot be represented in metadata. // [Attr<List<(int a, int b)>>] // 8 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<List<(int a, int b)>>").WithArguments("List<(int a, int b)>").WithLocation(17, 2), // (18,2): error CS8960: Type '(int a, string? b)' cannot be used in this context because it cannot be represented in metadata. // [Attr<(int a, string? b)>] // 9 Diagnostic(ErrorCode.ERR_AttrDependentTypeNotAllowed, "Attr<(int a, string? b)>").WithArguments("(int a, string? b)").WithLocation(18, 2)); } [Fact] public void GenericAttributeRestrictedTypeArgument() { var source = @" using System; class Attr<T> : Attribute { } [Attr<int*>] // 1 class C1 { } [Attr<delegate*<int, void>>] // 2 class C2 { } [Attr<TypedReference>] // 3 class C3 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,7): error CS0306: The type 'int*' may not be used as a type argument // [Attr<int*>] // 1 Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(5, 7), // (8,7): error CS0306: The type 'delegate*<int, void>' may not be used as a type argument // [Attr<delegate*<int, void>>] // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "delegate*<int, void>").WithArguments("delegate*<int, void>").WithLocation(8, 7), // (11,7): error CS0306: The type 'TypedReference' may not be used as a type argument // [Attr<TypedReference>] // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(11, 7)); } [Fact] public void GenericAttribute_AbstractStatic_01() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2Base : Attribute { public virtual void M() { } } class Attr2<T> : Attr2Base where T : I1 { public override void M() { T.M(); } } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { Console.Write(""C.M""); } } [Attr1<C>] [Attr2<C>] class C1 { public static void Main() { var attr2 = (Attr2Base)Attribute.GetCustomAttribute(typeof(C), typeof(Attr2Base)); attr2.M(); } } "; var comp = CreateCompilation(source, targetFramework: TargetFramework.Net60); comp.VerifyEmitDiagnostics(); } [Fact] public void GenericAttributeOnLambda() { var source = @" using System; class Attr<T> : Attribute { } class C { void M() { Func<string, string> x = [Attr<int>] (string x) => x; x(""a""); } } "; var verifier = CompileAndVerify(source, symbolValidator: validateMetadata, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifier.VerifyDiagnostics(); void validateMetadata(ModuleSymbol module) { var lambda = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c.<M>b__0_0"); var attrs = lambda.GetAttributes(); Assert.Equal(new[] { "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeSimilarToWellKnownAttribute() { var source = @" using System; class ObsoleteAttribute<T> : Attribute { } class C { [Obsolete<int>] void M0() { } void M1() => M0(); [Obsolete] void M2() { } void M3() => M2(); // 1 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS0612: 'C.M2()' is obsolete // void M3() => M2(); // 1 Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "M2()").WithArguments("C.M2()").WithLocation(15, 18)); } [Fact] public void GenericAttributesConsumeFromVB() { var csSource = @" using System; public class Attr<T> : Attribute { } [Attr<int>] public class C { } "; var comp = CreateCompilation(csSource); var vbSource = @" Public Class D Inherits C End Class "; var comp2 = CreateVisualBasicCompilation(vbSource, referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard).Concat(comp.EmitToImageReference())); var d = comp2.GetMember<INamedTypeSymbol>("D"); var attrs = d.BaseType.GetAttributes(); Assert.Equal(1, attrs.Length); Assert.Equal("Attr(Of System.Int32)", attrs[0].AttributeClass.ToTestDisplayString()); } [Fact] public void GenericAttribute_AbstractStatic_02() { var source = @" using System; class Attr1<T> : Attribute { } class Attr2<T> : Attribute where T : I1 { } interface I1 { static abstract void M(); } interface I2 : I1 { } class C : I1 { public static void M() { } } [Attr1<I1>] [Attr2<I1>] class C1 { } [Attr1<I2>] [Attr2<I2>] class C2 { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): error CS8919: Target runtime doesn't support static abstract members in interfaces. // static abstract void M(); Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, "M").WithLocation(8, 26), // (13,11): error CS8929: 'C.M()' cannot implement interface member 'I1.M()' in type 'C' because the target runtime doesn't support static abstract members in interfaces. // class C : I1 Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, "I1").WithArguments("C.M()", "I1.M()", "C").WithLocation(13, 11), // (19,8): error CS8920: The interface 'I1' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I1>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I1").WithArguments("Attr2<T>", "I1", "T", "I1").WithLocation(19, 8), // (23,8): error CS8920: The interface 'I2' cannot be used as type parameter 'T' in the generic type or method 'Attr2<T>'. The constraint interface 'I1' or its base interface has static abstract members. // [Attr2<I2>] Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers, "I2").WithArguments("Attr2<T>", "I1", "T", "I2").WithLocation(23, 8)); } [Fact] public void GenericAttributeProperty_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public T Prop { get; set; } } [Attr<string>(Prop = ""a"")] class Program { static void Main() { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Program)); foreach (var attr in attrs) { foreach (var arg in attr.NamedArguments) { Console.Write(arg.MemberName); Console.Write("" = ""); Console.Write(arg.TypedValue.Value); } } } } "; var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verify, expectedOutput: "Prop = a"); void verify(ModuleSymbol module) { var program = module.GlobalNamespace.GetMember<TypeSymbol>("Program"); var attrs = program.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(Prop = \"a\")" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeProperty_02() { var source = @" using System; class Attr<T1> : Attribute { public object Prop { get; set; } } class Outer<T2> { [Attr<object>(Prop = default(T2))] // 1 class Program1 { } [Attr<T2>(Prop = default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,26): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(Prop = default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 26), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,22): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(Prop = default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 22)); } [ConditionalFact(typeof(CoreClrOnly), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/56664"), WorkItem(55190, "https://github.com/dotnet/roslyn/issues/55190")] public void GenericAttributeParameter_01() { var source = @" using System; using System.Reflection; class Attr<T> : Attribute { public Attr(T param) { } } [Attr<string>(""a"")] class Holder { } class Program { static void Main() { try { var attrs = CustomAttributeData.GetCustomAttributes(typeof(Holder)); foreach (var attr in attrs) { foreach (var arg in attr.ConstructorArguments) { Console.Write(arg.Value); } } } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; // The expected output here will change once we consume a runtime // which has a fix for https://github.com/dotnet/runtime/issues/56492 var verifier = CompileAndVerify(source, sourceSymbolValidator: verify, symbolValidator: verifyMetadata, expectedOutput: "CustomAttributeFormatException"); verifier.VerifyTypeIL("Holder", @" .class private auto ansi beforefieldinit Holder extends [netstandard]System.Object { .custom instance void class Attr`1<string>::.ctor(!0) = ( 01 00 01 61 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2058 // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: ret } // end of method Holder::.ctor } // end of class Holder "); void verify(ModuleSymbol module) { var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>(\"a\")" }, GetAttributeStrings(attrs)); } void verifyMetadata(ModuleSymbol module) { // https://github.com/dotnet/roslyn/issues/55190 // The compiler should be able to read this attribute argument from metadata. // Once this is fixed, we should be able to use exactly the same 'verify' method for both source and metadata. var holder = module.GlobalNamespace.GetMember<TypeSymbol>("Holder"); var attrs = holder.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>" }, GetAttributeStrings(attrs)); } } [Fact] public void GenericAttributeParameter_02() { var source = @" using System; class Attr<T> : Attribute { public Attr(object param) { } } class Outer<T2> { [Attr<object>(default(T2))] // 1 class Program1 { } [Attr<T2>(default(T2))] // 2, 3 class Program2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,19): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<object>(default(T2))] // 1 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(7, 19), // (10,6): error CS8967: 'T2': an attribute type argument cannot use type parameters // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_AttrTypeArgCannotBeTypeVar, "Attr<T2>").WithArguments("T2").WithLocation(10, 6), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Attr<T2>(default(T2))] // 2, 3 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "default(T2)").WithLocation(10, 15)); } [Fact] public void GenericAttributeOnAssembly() { var source = @" using System; [assembly: Attr<string>] [assembly: Attr<int>] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class Attr<T> : Attribute { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verifySource); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)", "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } void verifySource(ModuleSymbol module) { var attrs = module.ContainingAssembly.GetAttributes(); Assert.Equal(new[] { "Attr<System.String>", "Attr<System.Int32>" }, GetAttributeStrings(attrs)); } } [ConditionalFact(typeof(CoreClrOnly))] public void GenericAttributeReflection_OpenGeneric() { var source = @" using System; class Attr<T> : Attribute { } class Attr2<T> : Attribute { } [Attr<string>] [Attr2<int>] class Holder { } class Program { static void Main() { try { var attr = Attribute.GetCustomAttribute(typeof(Holder), typeof(Attr<>)); Console.Write(attr?.ToString() ?? ""not found""); } catch (Exception e) { Console.Write(e.GetType().Name); } } } "; var verifier = CompileAndVerify(source, expectedOutput: "not found"); verifier.VerifyDiagnostics(); } [Fact] public void GenericAttributeNested() { var source = @" using System; class Attr<T> : Attribute { } [Attr<Attr<string>>] class C { } "; var verifier = CompileAndVerify(source, symbolValidator: verify, sourceSymbolValidator: verify); verifier.VerifyDiagnostics(); void verify(ModuleSymbol module) { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var attrs = c.GetAttributes(); Assert.Equal(new[] { "Attr<Attr<System.String>>" }, GetAttributeStrings(attrs)); } } #endregion } }
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/Semantic/Semantics/InitOnlyMemberTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InitOnlyMemberTests Inherits BasicTestBase Protected Const IsExternalInitTypeDefinition As String = " namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } " <Fact> Public Sub EvaluationInitOnlySetter_01() Dim csSource = " public class C : System.Attribute { public int Property0 { init { System.Console.Write(value + "" 0 ""); } } public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } public int Property6 { init { System.Console.Write(value + "" 6 ""); } } public int Property7 { init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() With { .Property1 = 42, .Property2 = 43} End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Me.GetType().GetCustomAttributes(False) End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 48 7 42 1 43 2 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_02() Dim csSource = " public class C : System.Attribute { public int Property0 { init; get; } public int Property1 { init; get; } public int Property2 { init; get; } public int Property3 { init; get; } public int Property4 { init; get; } public int Property5 { init; get; } public int Property6 { init; get; } public int Property7 { init; get; } public int Property8 { init; get; } public int Property9 { init => throw new System.InvalidOperationException(); get => 0; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() With { .Property1 = 42 } System.Console.Write(b.Property0) System.Console.Write(" "c) System.Console.Write(b.Property1) System.Console.Write(" "c) System.Console.Write(b.Property2) System.Console.Write(" "c) System.Console.Write(b.Property3) System.Console.Write(" "c) System.Console.Write(b.Property4) System.Console.Write(" "c) System.Console.Write(b.Property5) System.Console.Write(" "c) System.Console.Write(b.Property6) System.Console.Write(" "c) System.Console.Write(DirectCast(b.GetType().GetCustomAttributes(False)(0), C).Property7) System.Console.Write(" "c) System.Console.Write(b.Property8) B.Init(b.Property9, 492) B.Init((b.Property9), 493) End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Init(Property2, 43) Init((Property2), 430) With Me Init(.Property8, 49) Init((.Property9), 494) End With Dim b = Me Init(b.Property9, 490) Init((b.Property9), 491) With b Init(.Property9, 499) Init((.Property9), 450) End With Test() Dim d = Sub() Init(Property9, 600) Init((Property9), 601) End Sub d() End Sub Public Sub Test() With Me Init(.Property9, 495) Init((.Property9), 496) End With Init(Property9, 497) Init((Property9), 498) Dim b = Me With b Init(.Property9, 451) Init((.Property9), 452) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46 47 48 49").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim b = new B() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Property9, 492) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property2, 43) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property8, 49) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Property9, 490) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 499) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 600) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 495) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 497) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 451) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_03() Dim csSource = " public class C { public int this[int x] { init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me.Item(0) = 41 MyBase.Item(0) = 42 MyClass.Item(0) = 43 Me(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) = 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) = 42 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) = 44 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) = 45 ~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(0) = 41 With New B() .Item(0) = 42 End With Dim y As New B() With { .F = Sub() .Item(0) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) = 44 End With With Me With y .Item(0) = 45 End With End With Dim x as New B() x(0) = 46 x.Item(0) = 47 Dim z = Sub() Item(0) = 48 Me(0) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(0) = 41 Me.Item(0) = 42 MyBase.Item(0) = 43 MyClass.Item(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_04() Dim csSource = " public class C : System.Attribute { private int[] _item = new int[36]; public int this[int x] { init { if (x > 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b(9), 49) B.Init((b(19)), 59) B.Init(b.Item(10), 50) B.Init((b.Item(20)), 60) With b B.Init(.Item(11), 51) B.Init((.Item(21)), 61) End With for i as Integer = 0 To 35 System.Console.Write(b(i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With Init(Item(6), 46) Init((Item(22)), 62) Init(Me(7), 47) Init((Me(23)), 63) Dim b = Me Init(b(12), 52) Init((b(24)), 64) Init(b.Item(13), 53) Init((b.Item(25)), 65) With Me Init(.Item(8), 48) Init((.Item(26)), 66) End With With b Init(.Item(14), 54) Init((.Item(27)), 67) End With Test() Dim d = Sub() Init(Item(32), 72) Init((Item(33)), 73) Init(Me(34), 74) Init((Me(35)), 75) End Sub d() End Sub Public Sub Test() With Me Init(.Item(15), 55) Init((.Item(28)), 68) End With Init(Me(16), 56) Init((Me(29)), 69) Init(Item(17), 57) Init((Item(30)), 70) Dim b = Me With b Init(.Item(18), 58) Init((.Item(31)), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b(9), 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Item(10), 50) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(.Item(11), 51) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(1) = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(5) = 45 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(6), 46) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(7), 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b(12), 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Item(13), 53) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(8), 48) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(14), 54) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(32), 72) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(34), 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(15), 55) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(16), 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(17), 57) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(18), 58) ~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(1) = 41 With New B() .Item(2) = 42 End With Dim y As New B() With { .F = Sub() .Item(3) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(4) = 44 End With With Me With y .Item(5) = 45 End With End With Dim x as New B() x(6) = 46 x.Item(7) = 47 Dim z = Sub() Item(8) = 48 Me(9) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(1) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(2) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(3) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(4) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(6) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(7) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(8) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(9) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(1) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_05() Dim csSource = " public class C { public int Property0 { get => 0; init { System.Console.Write(value + "" 0 ""); } } public int Property1 { get => 0; init { System.Console.Write(value + "" 1 ""); } } public int Property2 { get => 0; init { System.Console.Write(value + "" 2 ""); } } public int Property3 { get => 0; init { System.Console.Write(value + "" 3 ""); } } public int Property4 { get => 0; init { System.Console.Write(value + "" 4 ""); } } public int Property5 { get => 0; init { System.Console.Write(value + "" 5 ""); } } public int Property6 { get => 0; init { System.Console.Write(value + "" 6 ""); } } public int Property7 { get => 0; init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x as New B() End Sub End Class Class B Inherits C Public Sub New() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 += 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 += 47 ~~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 += 42 With New B() .Property2 += 43 End With Dim y As New B() With { .F = Sub() .Property3 += 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 += 45 End With With Me With y .Property6 += 47 End With End With Dim x as New B() x.Property0 += 41 Dim z = Sub() Property5 += 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 += 42 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 += 43 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 += 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 += 45 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 += 41 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 += 46 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_06() Dim csSource = " public class C { public int this[int x] { get => 0; init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) += 40 Me.Item(0) += 41 MyBase.Item(0) += 42 MyClass.Item(0) += 43 Me(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) += 40 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) += 41 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) += 42 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) += 44 ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) += 45 ~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) += 40 x.Item(0) += 41 With New B() .Item(0) += 42 End With Dim y As New B() With { .F = Sub() .Item(0) += 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) += 44 End With With Me With y .Item(0) += 45 End With End With Dim x as New B() x(0) += 46 x.Item(0) += 47 Dim z = Sub() Item(0) += 48 Me(0) += 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 40 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 42 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 43 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 44 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 46 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 48 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 49 ~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) += 40 Me(0) += 41 Me.Item(0) += 42 MyBase.Item(0) += 43 MyClass.Item(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 40 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 41 ~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) += 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) += 44 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_07() Dim csSource = " public interface I { public int Property1 { init; } public int Property2 { init; } public int Property3 { init; } public int Property4 { init; } public int Property5 { init; } } public class C : I { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() M1(Of C)() M2(Of B)() End Sub Shared Sub M1(OF T As {New, I})() Dim x = new T() With { .Property1 = 42 } End Sub Shared Sub M2(OF T As {New, C})() Dim x = new T() With { .Property2 = 43 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 43 2 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property2 = 43 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub Shared Sub M1(Of T As {New, I})() Dim x = New T() x.Property1 = 42 With New T() .Property2 = 43 End With End Sub Shared Sub M2(Of T As {New, C})() Dim x = New T() x.Property3 = 44 With New T() .Property4 = 45 End With End Sub Shared Sub M3(x As I) x.Property5 = 46 End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property3 = 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property5 = 46 ~~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_08() Dim csSource = " using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { public int Property1 { init; } public int Property2 { init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C : I { int I.Property1 { init { System.Console.Write(value + "" 1 ""); } } int I.Property2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new I() With { .Property1 = 42 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new I() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() With New I() .Property2 = 43 End With End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_09() Dim csSource = " public class C { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Shared Sub New() Property1 = 41 Me.Property2 = 42 MyBase.Property3 = 43 MyClass.Property4 = 44 With Me .Property5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Property1 = 41 ~~~~~~~~~ BC30043: 'Me' is valid only within an instance method. Me.Property2 = 42 ~~ BC30043: 'MyBase' is valid only within an instance method. MyBase.Property3 = 43 ~~~~~~ BC30043: 'MyClass' is valid only within an instance method. MyClass.Property4 = 44 ~~~~~~~ BC30043: 'Me' is valid only within an instance method. With Me ~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property5 = 45 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_10() Dim csSource = " public class C { public int P2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() With (Me) .P2 = 42 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 2 ").VerifyDiagnostics() End Sub <Fact> Public Sub Overriding_01() Dim csSource = " public class C { public virtual int P0 { init { } } public virtual int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C Public Overrides WriteOnly Property P0 As Integer Set End Set End Property Public Overrides Property P1 As Integer End Class Class B2 Inherits C Public Overrides Property P0 As Integer Public Overrides ReadOnly Property P1 As Integer End Class Class B3 Inherits C Public Overrides ReadOnly Property P0 As Integer Public Overrides WriteOnly Property P1 As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property P0 As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Property P0 As Integer'. Public Overrides WriteOnly Property P0 As Integer ~~ BC37312: 'Public Overrides Property P1 As Integer' cannot override init-only 'Public Overridable Overloads Property P1 As Integer'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P0 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P1 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P0 As Integer ~~ BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.True(p1Set.OverriddenMethod.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_02() Dim csSource = " public class C<T> { public virtual T this[int x] { init { } } public virtual T this[short x] { init {} get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C(Of Integer) Public Overrides WriteOnly Property Item(x as Integer) As Integer Set End Set End Property Public Overrides Property Item(x as Short) As Integer Get Return Nothing End Get Set End Set End Property End Class Class B2 Inherits C(Of Integer) Public Overrides Property Item(x as Integer) As Integer Get Return Nothing End Get Set End Set End Property Public Overrides ReadOnly Property Item(x as Short) As Integer Get Return Nothing End Get End Property End Class Class B3 Inherits C(Of Integer) Public Overrides ReadOnly Property Item(x as Integer) As Integer Get Return Nothing End Get End Property Public Overrides WriteOnly Property Item(x as Short) As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property Item(x As Integer) As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer'. Public Overrides WriteOnly Property Item(x as Integer) As Integer ~~~~ BC37312: 'Public Overrides Property Item(x As Short) As Integer' cannot override init-only 'Public Overridable Overloads Default Property Item(x As Short) As Integer'. Public Overrides Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides WriteOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property Item(x as Short) As Integer ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetTypeByMetadataName("B1").GetMembers("Item").OfType(Of PropertySymbol).First().SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Assert.True(DirectCast(p0Set.OverriddenMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_03() Dim csSource = " public class A { public virtual int P1 { init; get; } public virtual int P2 { init; get; } } public class B : A { public override int P1 { get => throw null; } public override int P2 { init {} } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class C1 Inherits B Public Overrides WriteOnly Property P1 As Integer Set End Set End Property Public Overrides WriteOnly Property P2 As Integer Set End Set End Property End Class Class C2 Inherits B Public Overrides Property P1 As Integer Public Overrides Property P2 As Integer End Class Class C3 Inherits B Public Overrides ReadOnly Property P1 As Integer Public Overrides ReadOnly Property P2 As Integer End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ BC37312: 'Public Overrides WriteOnly Property P2 As Integer' cannot override init-only 'Public Overrides WriteOnly Property P2 As Integer'. Public Overrides WriteOnly Property P2 As Integer ~~ BC30362: 'Public Overrides Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P2 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P2 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Overriding_04() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_05() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_06() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_07() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.OverriddenMethod.IsInitOnly) Assert.NotEmpty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_08() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL1::get_P1() .set instance void CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL1::get_P2() .set instance void CL1::set_P2(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P2(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit CL2 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P1(int32) } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P2(int32) } } .class public auto ansi beforefieldinit CL3 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL3::get_P1() .set instance void CL3::set_P1(int32) } .method public hidebysig virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL3::get_P2() .set instance void CL3::set_P2(int32) } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) Dim cl2p1 = compilation.GetMember(Of PropertySymbol)("CL2.P1") Assert.NotEmpty(cl2p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.OverriddenProperty.TypeCustomModifiers) Dim cl2p2 = compilation.GetMember(Of PropertySymbol)("CL2.P2") Assert.NotEmpty(cl2p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.OverriddenProperty.TypeCustomModifiers) Dim cl3p1 = compilation.GetMember(Of PropertySymbol)("CL3.P1") Assert.Empty(cl3p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.OverriddenProperty.TypeCustomModifiers) Dim cl3p2 = compilation.GetMember(Of PropertySymbol)("CL3.P2") Assert.Empty(cl3p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.OverriddenProperty.TypeCustomModifiers) End Sub <Fact> Public Sub Implementing_01() Dim csSource = " public interface I { int P0 { init; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property P0 As Integer Implements I.P0 Set End Set End Property Public Property P1 As Integer Implements I.P1 End Class Class B2 Implements I Public Property P0 As Integer Implements I.P0 Public ReadOnly Property P1 As Integer Implements I.P1 End Class Class B3 Implements I Public ReadOnly Property P0 As Integer Implements I.P0 Public WriteOnly Property P1 As Integer Implements I.P1 Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public WriteOnly Property P0 As Integer Implements I.P0 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P1 As Integer Implements I.P1 ~~~~ BC31444: 'WriteOnly Property P0 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_02() Dim csSource = " public interface I { int this[int x] { init; } int this[short x] { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item Set End Set End Property Public Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property End Class Class B2 Implements I Public Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property Public ReadOnly Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get End Property End Class Class B3 Implements I Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get End Property Public WriteOnly Property Item(x As Short) As Integer Implements I.Item Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC31444: 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_03() Dim csSource = " public interface I { int P0 { set; get; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B2 Implements I Public Property P0 As Integer Implements I.P0, I.P1 End Class Class B3 Implements I Public Property P0 As Integer Implements I.P1, I.P0 End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0, I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P1, I.P0 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Implementing_04() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.Empty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact()> Public Sub Implementing_05() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.NotEmpty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact> Public Sub LateBound_01() Dim csSource = " public class C { public int P0 { init; get; } public int P1 { init; get; } public int P2 { init; get; } public int P3 { init; get; } private int[] _item = new int[10]; public int this[int x] { init => _item[x] = value; get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox.P0 = -40 b.Init(ox.P1, -41) ob.Init(x.P2, -42) ob.Init(ox.P3, -43) ox(0) = 40 ox.Item(1) = 41 b.Init(ox(2), 42) ob.Init(x(3), 43) b.Init(ox.Item(4), 44) ob.Init(x.Item(5), 45) ob.Init(ox(6), 46) ob.Init(ox.Item(7), 47) System.Console.Write(x.P0) System.Console.Write(" ") System.Console.Write(x.P1) System.Console.Write(" ") System.Console.Write(x.P2) System.Console.Write(" ") System.Console.Write(x.P3) For i as Integer = 0 To 7 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "-40 -41 0 -43 40 41 42 0 44 0 46 47" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub LateBound_02() Dim csSource = " public class C { private int[] _item = new int[12]; public int this[int x] { init => _item[x] = value; get => _item[x]; } public int this[short x] { init => throw null; get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox(0) = 40 ox.Item(1) = 41 x(CObj(2)) = 42 x.Item(CObj(3)) = 43 b.Init(ox(4), 44) ob.Init(ox(5), 45) b.Init(ox.Item(6), 46) ob.Init(ox.Item(7), 47) b.Init(x(CObj(8)), 48) ob.Init(x(CObj(9)), 49) b.Init(x.Item(CObj(10)), 50) ob.Init(x.Item(CObj(11)), 51) System.Console.Write(x(0)) For i as Integer = 1 To 11 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "40 41 42 43 44 45 46 47 48 49 50 51" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub Redim_01() Dim csSource = " public class C { public int[] Property0 { init; get; } public int[] Property1 { init; get; } public int[] Property2 { init; get; } public int[] Property3 { init; get; } public int[] Property4 { init; get; } public int[] Property5 { init; get; } public int[] Property6 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0.Length) System.Console.Write(" "c) System.Console.Write(b.Property3.Length) System.Console.Write(" "c) System.Console.Write(b.Property4.Length) System.Console.Write(" "c) System.Console.Write(b.Property5.Length) System.Console.Write(" "c) System.Console.Write(b.Property6.Length) End Sub End Class Class B Inherits C Public Sub New() ReDim Property0(41) Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me Redim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 45 46 47 48").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Property0(41) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim .Property6(47) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x.Property1(42) With New B() Redim .Property2(43) End With Dim y As New B() With { .F = Sub() ReDim .Property3(44) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Redim .Property4(45) End With With Me With y Redim .Property6(47) End With End With Dim x as New B() Redim x.Property0(41) Dim z = Sub() Redim Property5(46) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Property1(42) ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property2(43) ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property3(44) ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property4(45) ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property6(47) ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim x.Property0(41) ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim Property5(46) ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Property0(41) ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me ReDim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Property0(41) ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property6(47) ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Redim_02() Dim csSource = " public class C { private int[][] _item = new int[6][]; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i).Length) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Item(0)(40) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim .Item(5)(45) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x(0)(40) ReDim x.Item(1)(41) With New B() ReDim .Item(2)(42) End With Dim y As New B() With { .F = Sub() ReDim .Item(3)(43) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y ReDim .Item(4)(44) End With With Me With y ReDim .Item(5)(45) End With End With Dim x as New B() ReDim x(6)(46) ReDim x.Item(7)(47) Dim z = Sub() ReDim Item(8)(48) ReDim Me(9)(49) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(0)(40) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(1)(41) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(2)(42) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(3)(43) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(4)(44) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(6)(46) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(7)(47) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(8)(48) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(9)(49) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(0)(40) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_01() Dim csSource = " public class C { public int[] Property0 { init; get; } = new int[] {}; public int[] Property1 { init; get; } = new int[] {}; public int[] Property2 { init; get; } = new int[] {}; public int[] Property3 { init; get; } = new int[] {}; public int[] Property4 { init; get; } = new int[] {}; public int[] Property5 { init; get; } = new int[] {}; public int[] Property6 { init; get; } = new int[] {}; } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property3 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property4 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property5 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property6 Is Nothing) End Sub End Class Class B Inherits C Public Sub New() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Property0 ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Property6 ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x.Property1 With New B() Erase .Property2 End With Dim y As New B() With { .F = Sub() Erase .Property3 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Property4 End With With Me With y Erase .Property6 End With End With Dim x as New B() Erase x.Property0 Dim z = Sub() Erase Property5 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property1 ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property2 ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property3 ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property4 ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property0 ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property5 ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property0 ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_02() Dim csSource = " public class C { private int[][] _item = new int[6][] {new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}}; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i) Is Nothing) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True True ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Item(0) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Item(5) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x(0) Erase x.Item(1) With New B() Erase .Item(2) End With Dim y As New B() With { .F = Sub() Erase .Item(3) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Item(4) End With With Me With y Erase .Item(5) End With End With Dim x as New B() Erase x(6) Erase x.Item(7) Dim z = Sub() Erase Item(8) Erase Me(9) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(0) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(1) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(2) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(3) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(4) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(6) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(7) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(8) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(9) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(0) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub DictionaryAccess_01() Dim csSource = " public class C { private int[] _item = new int[36]; public int this[string id] { init { int x = int.Parse(id.Substring(1, id.Length - 1)); if (x != 1 && x != 5 && x != 7 && x != 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get { int x = int.Parse(id.Substring(1, id.Length - 1)); return _item[x]; } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b!c9, 49) B.Init((b!c19), 59) With b B.Init(!c11, 51) B.Init((!c21), 61) End With for i as Integer = 0 To 35 System.Console.Write(b("c" & i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Me!c1 = 41 With Me !c5 = 45 End With Init(Me!c7, 47) Init((Me!c23), 63) Dim b = Me Init(b!c12, 52) Init((b!c24), 64) With Me Init(!c8, 48) Init((!c26), 66) End With With b Init(!c14, 54) Init((!c27), 67) End With Test() Dim d = Sub() Init(Me!c34, 74) Init((Me!c35), 75) End Sub d() End Sub Public Sub Test() With Me Init(!c15, 55) Init((!c28), 68) End With Init(Me!c16, 56) Init((Me!c29), 69) Dim b = Me With b Init(!c18, 58) Init((!c31), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="0 41 0 0 0 45 0 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b!c9, 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(!c11, 51) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me!c1 = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. !c5 = 45 ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c7, 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b!c12, 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c8, 48) ~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c14, 54) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c34, 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c15, 55) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c16, 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c18, 58) ~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x!c0 = 40 With New B() !c2 = 42 End With Dim y As New B() With { .F = Sub() !c3 = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y !c4 = 44 End With With Me With y !c5 = 45 End With End With Dim x as New B() x!c6 = 46 Dim z = Sub() Me!c9 = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c0 = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c2 = 42 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c3 = 43 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c4 = 44 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c6 = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c9 = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Me!c1 = 41 With Me !c5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c1 = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnSetAccessorParameter() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Set ~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. c.Property1 = 42 ~~~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetAccessorParameter_AndProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Public Overrides WriteOnly Property Property1 As Integer ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 42 ~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. C.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnInstanceMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig instance void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. c.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. C.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetterOfRefProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property1() { .get instance int32& C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnRefReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property1() .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Dim x2 = c.Property1 ~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnPropertyAndGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 2 ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModOptOnSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modopt(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modopt(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Shared Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Theory, InlineData("Runtime.CompilerServices.IsExternalInit"), InlineData("CompilerServices.IsExternalInit"), InlineData("IsExternalInit"), InlineData("ns.System.Runtime.CompilerServices.IsExternalInit"), InlineData("system.Runtime.CompilerServices.IsExternalInit"), InlineData("System.runtime.CompilerServices.IsExternalInit"), InlineData("System.Runtime.compilerServices.IsExternalInit"), InlineData("System.Runtime.CompilerServices.isExternalInit") > Public Sub IsExternalInitCheck(modifierName As String) Dim ilSource = " .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modreq(" + modifierName + ") set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modreq(" + modifierName + ") C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit " + modifierName + " extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } " Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. c.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub IsInitOnlyValue() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) Dim vbSource2 = <compilation> <file name="c.vb"><![CDATA[ Class Test1(Of T) Public Shared Sub M1() Dim x as Integer = 0 x.DoSomething() End Sub Public Function M2() As System.Action return Sub() End Sub End Function Public Property P As Integer End Class Class Test2 Inherits Test1(Of Integer) End Class Delegate Sub D() Module Ext <System.Runtime.CompilerServices.Extension> Sub DoSomething(x As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilation(vbSource2, references:={compilation1.ToMetadataReference()}, options:=TestOptions.ReleaseDll) Dim tree = compilation2.SyntaxTrees.Single() Dim model = compilation2.GetSemanticModel(tree) Dim lambda = tree.GetRoot.DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(lambda).Symbol, MethodSymbol).IsInitOnly) Dim invocation = tree.GetRoot.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(invocation).Symbol, MethodSymbol).IsInitOnly) Dim verify = Sub(compilation As VisualBasicCompilation) Dim test1 = compilation.GetTypeByMetadataName("Test1`1") Dim p = test1.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim test1Constructed = compilation.GetTypeByMetadataName("Test2").BaseTypeNoUseSiteDiagnostics p = test1Constructed.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim d = compilation.GetTypeByMetadataName("D") For Each m As MethodSymbol In d.GetMembers() Assert.False(m.IsInitOnly) Next End Sub verify(compilation2) Dim compilation3 = CreateCompilation(vbSource1, references:={compilation2.ToMetadataReference()}, options:=TestOptions.ReleaseDll) verify(compilation3) End Sub <Fact> Public Sub ReferenceConversion_01() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_02() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_03() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() TryCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. TryCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_04() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With TryCast(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_05() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() CType(MyBase, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(MyBase, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. CType(MyBase, I1).P1 = 41 ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_06() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(MyClass, I1).P1 = 41 With MyClass .P0 = 1 End With With MyBase .P0 = 2 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. With MyClass ~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. With MyBase ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_07() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Class B Inherits C Public Sub New() Me.P0 = 41 End Sub End Class Class D Public Shared Widening Operator CType(x As D) As B Return Nothing End Operator Public Sub New() CType(Me, B).P0 = 42 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, B).P0 = 42 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_08() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, B).P0 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, B).P0 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_09() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, B) .P0 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P0 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_10() Dim csSource = " public interface I1 { int P1 { get; init; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Structure B Implements I1 Public Sub New(x As Integer) DirectCast(Me, I1).P1 = 41 CType(Me, I1).P1 = 42 DirectCast(CObj(Me), I1).P1 = 43 End Sub End Structure ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC30149: Structure 'B' must implement 'Property P1 As Integer' for interface 'I1'. Implements I1 ~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, I1).P1 = 42 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(CObj(Me), I1).P1 = 43 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InitOnlyMemberTests Inherits BasicTestBase Protected Const IsExternalInitTypeDefinition As String = " namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } " <Fact> Public Sub EvaluationInitOnlySetter_01() Dim csSource = " public class C : System.Attribute { public int Property0 { init { System.Console.Write(value + "" 0 ""); } } public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } public int Property6 { init { System.Console.Write(value + "" 6 ""); } } public int Property7 { init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() With { .Property1 = 42, .Property2 = 43} End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Me.GetType().GetCustomAttributes(False) End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 48 7 42 1 43 2 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_02() Dim csSource = " public class C : System.Attribute { public int Property0 { init; get; } public int Property1 { init; get; } public int Property2 { init; get; } public int Property3 { init; get; } public int Property4 { init; get; } public int Property5 { init; get; } public int Property6 { init; get; } public int Property7 { init; get; } public int Property8 { init; get; } public int Property9 { init => throw new System.InvalidOperationException(); get => 0; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() With { .Property1 = 42 } System.Console.Write(b.Property0) System.Console.Write(" "c) System.Console.Write(b.Property1) System.Console.Write(" "c) System.Console.Write(b.Property2) System.Console.Write(" "c) System.Console.Write(b.Property3) System.Console.Write(" "c) System.Console.Write(b.Property4) System.Console.Write(" "c) System.Console.Write(b.Property5) System.Console.Write(" "c) System.Console.Write(b.Property6) System.Console.Write(" "c) System.Console.Write(DirectCast(b.GetType().GetCustomAttributes(False)(0), C).Property7) System.Console.Write(" "c) System.Console.Write(b.Property8) B.Init(b.Property9, 492) B.Init((b.Property9), 493) End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Init(Property2, 43) Init((Property2), 430) With Me Init(.Property8, 49) Init((.Property9), 494) End With Dim b = Me Init(b.Property9, 490) Init((b.Property9), 491) With b Init(.Property9, 499) Init((.Property9), 450) End With Test() Dim d = Sub() Init(Property9, 600) Init((Property9), 601) End Sub d() End Sub Public Sub Test() With Me Init(.Property9, 495) Init((.Property9), 496) End With Init(Property9, 497) Init((Property9), 498) Dim b = Me With b Init(.Property9, 451) Init((.Property9), 452) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46 47 48 49").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim b = new B() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Property9, 492) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property2, 43) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property8, 49) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Property9, 490) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 499) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 600) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 495) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 497) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 451) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_03() Dim csSource = " public class C { public int this[int x] { init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me.Item(0) = 41 MyBase.Item(0) = 42 MyClass.Item(0) = 43 Me(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) = 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) = 42 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) = 44 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) = 45 ~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(0) = 41 With New B() .Item(0) = 42 End With Dim y As New B() With { .F = Sub() .Item(0) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) = 44 End With With Me With y .Item(0) = 45 End With End With Dim x as New B() x(0) = 46 x.Item(0) = 47 Dim z = Sub() Item(0) = 48 Me(0) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(0) = 41 Me.Item(0) = 42 MyBase.Item(0) = 43 MyClass.Item(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_04() Dim csSource = " public class C : System.Attribute { private int[] _item = new int[36]; public int this[int x] { init { if (x > 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b(9), 49) B.Init((b(19)), 59) B.Init(b.Item(10), 50) B.Init((b.Item(20)), 60) With b B.Init(.Item(11), 51) B.Init((.Item(21)), 61) End With for i as Integer = 0 To 35 System.Console.Write(b(i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With Init(Item(6), 46) Init((Item(22)), 62) Init(Me(7), 47) Init((Me(23)), 63) Dim b = Me Init(b(12), 52) Init((b(24)), 64) Init(b.Item(13), 53) Init((b.Item(25)), 65) With Me Init(.Item(8), 48) Init((.Item(26)), 66) End With With b Init(.Item(14), 54) Init((.Item(27)), 67) End With Test() Dim d = Sub() Init(Item(32), 72) Init((Item(33)), 73) Init(Me(34), 74) Init((Me(35)), 75) End Sub d() End Sub Public Sub Test() With Me Init(.Item(15), 55) Init((.Item(28)), 68) End With Init(Me(16), 56) Init((Me(29)), 69) Init(Item(17), 57) Init((Item(30)), 70) Dim b = Me With b Init(.Item(18), 58) Init((.Item(31)), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b(9), 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Item(10), 50) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(.Item(11), 51) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(1) = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(5) = 45 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(6), 46) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(7), 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b(12), 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Item(13), 53) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(8), 48) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(14), 54) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(32), 72) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(34), 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(15), 55) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(16), 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(17), 57) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(18), 58) ~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(1) = 41 With New B() .Item(2) = 42 End With Dim y As New B() With { .F = Sub() .Item(3) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(4) = 44 End With With Me With y .Item(5) = 45 End With End With Dim x as New B() x(6) = 46 x.Item(7) = 47 Dim z = Sub() Item(8) = 48 Me(9) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(1) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(2) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(3) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(4) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(6) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(7) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(8) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(9) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(1) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_05() Dim csSource = " public class C { public int Property0 { get => 0; init { System.Console.Write(value + "" 0 ""); } } public int Property1 { get => 0; init { System.Console.Write(value + "" 1 ""); } } public int Property2 { get => 0; init { System.Console.Write(value + "" 2 ""); } } public int Property3 { get => 0; init { System.Console.Write(value + "" 3 ""); } } public int Property4 { get => 0; init { System.Console.Write(value + "" 4 ""); } } public int Property5 { get => 0; init { System.Console.Write(value + "" 5 ""); } } public int Property6 { get => 0; init { System.Console.Write(value + "" 6 ""); } } public int Property7 { get => 0; init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x as New B() End Sub End Class Class B Inherits C Public Sub New() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 += 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 += 47 ~~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 += 42 With New B() .Property2 += 43 End With Dim y As New B() With { .F = Sub() .Property3 += 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 += 45 End With With Me With y .Property6 += 47 End With End With Dim x as New B() x.Property0 += 41 Dim z = Sub() Property5 += 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 += 42 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 += 43 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 += 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 += 45 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 += 41 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 += 46 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_06() Dim csSource = " public class C { public int this[int x] { get => 0; init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) += 40 Me.Item(0) += 41 MyBase.Item(0) += 42 MyClass.Item(0) += 43 Me(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) += 40 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) += 41 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) += 42 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) += 44 ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) += 45 ~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) += 40 x.Item(0) += 41 With New B() .Item(0) += 42 End With Dim y As New B() With { .F = Sub() .Item(0) += 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) += 44 End With With Me With y .Item(0) += 45 End With End With Dim x as New B() x(0) += 46 x.Item(0) += 47 Dim z = Sub() Item(0) += 48 Me(0) += 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 40 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 42 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 43 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 44 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 46 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 48 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 49 ~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) += 40 Me(0) += 41 Me.Item(0) += 42 MyBase.Item(0) += 43 MyClass.Item(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 40 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 41 ~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) += 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) += 44 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_07() Dim csSource = " public interface I { public int Property1 { init; } public int Property2 { init; } public int Property3 { init; } public int Property4 { init; } public int Property5 { init; } } public class C : I { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() M1(Of C)() M2(Of B)() End Sub Shared Sub M1(OF T As {New, I})() Dim x = new T() With { .Property1 = 42 } End Sub Shared Sub M2(OF T As {New, C})() Dim x = new T() With { .Property2 = 43 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 43 2 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property2 = 43 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub Shared Sub M1(Of T As {New, I})() Dim x = New T() x.Property1 = 42 With New T() .Property2 = 43 End With End Sub Shared Sub M2(Of T As {New, C})() Dim x = New T() x.Property3 = 44 With New T() .Property4 = 45 End With End Sub Shared Sub M3(x As I) x.Property5 = 46 End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property3 = 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property5 = 46 ~~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_08() Dim csSource = " using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { public int Property1 { init; } public int Property2 { init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C : I { int I.Property1 { init { System.Console.Write(value + "" 1 ""); } } int I.Property2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new I() With { .Property1 = 42 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new I() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() With New I() .Property2 = 43 End With End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_09() Dim csSource = " public class C { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Shared Sub New() Property1 = 41 Me.Property2 = 42 MyBase.Property3 = 43 MyClass.Property4 = 44 With Me .Property5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Property1 = 41 ~~~~~~~~~ BC30043: 'Me' is valid only within an instance method. Me.Property2 = 42 ~~ BC30043: 'MyBase' is valid only within an instance method. MyBase.Property3 = 43 ~~~~~~ BC30043: 'MyClass' is valid only within an instance method. MyClass.Property4 = 44 ~~~~~~~ BC30043: 'Me' is valid only within an instance method. With Me ~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property5 = 45 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_10() Dim csSource = " public class C { public int P2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() With (Me) .P2 = 42 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 2 ").VerifyDiagnostics() End Sub <Fact> Public Sub Overriding_01() Dim csSource = " public class C { public virtual int P0 { init { } } public virtual int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C Public Overrides WriteOnly Property P0 As Integer Set End Set End Property Public Overrides Property P1 As Integer End Class Class B2 Inherits C Public Overrides Property P0 As Integer Public Overrides ReadOnly Property P1 As Integer End Class Class B3 Inherits C Public Overrides ReadOnly Property P0 As Integer Public Overrides WriteOnly Property P1 As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property P0 As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Property P0 As Integer'. Public Overrides WriteOnly Property P0 As Integer ~~ BC37312: 'Public Overrides Property P1 As Integer' cannot override init-only 'Public Overridable Overloads Property P1 As Integer'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P0 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P1 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P0 As Integer ~~ BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.True(p1Set.OverriddenMethod.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_02() Dim csSource = " public class C<T> { public virtual T this[int x] { init { } } public virtual T this[short x] { init {} get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C(Of Integer) Public Overrides WriteOnly Property Item(x as Integer) As Integer Set End Set End Property Public Overrides Property Item(x as Short) As Integer Get Return Nothing End Get Set End Set End Property End Class Class B2 Inherits C(Of Integer) Public Overrides Property Item(x as Integer) As Integer Get Return Nothing End Get Set End Set End Property Public Overrides ReadOnly Property Item(x as Short) As Integer Get Return Nothing End Get End Property End Class Class B3 Inherits C(Of Integer) Public Overrides ReadOnly Property Item(x as Integer) As Integer Get Return Nothing End Get End Property Public Overrides WriteOnly Property Item(x as Short) As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property Item(x As Integer) As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer'. Public Overrides WriteOnly Property Item(x as Integer) As Integer ~~~~ BC37312: 'Public Overrides Property Item(x As Short) As Integer' cannot override init-only 'Public Overridable Overloads Default Property Item(x As Short) As Integer'. Public Overrides Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides WriteOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property Item(x as Short) As Integer ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetTypeByMetadataName("B1").GetMembers("Item").OfType(Of PropertySymbol).First().SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Assert.True(DirectCast(p0Set.OverriddenMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_03() Dim csSource = " public class A { public virtual int P1 { init; get; } public virtual int P2 { init; get; } } public class B : A { public override int P1 { get => throw null; } public override int P2 { init {} } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class C1 Inherits B Public Overrides WriteOnly Property P1 As Integer Set End Set End Property Public Overrides WriteOnly Property P2 As Integer Set End Set End Property End Class Class C2 Inherits B Public Overrides Property P1 As Integer Public Overrides Property P2 As Integer End Class Class C3 Inherits B Public Overrides ReadOnly Property P1 As Integer Public Overrides ReadOnly Property P2 As Integer End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ BC37312: 'Public Overrides WriteOnly Property P2 As Integer' cannot override init-only 'Public Overrides WriteOnly Property P2 As Integer'. Public Overrides WriteOnly Property P2 As Integer ~~ BC30362: 'Public Overrides Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P2 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P2 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Overriding_04() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_05() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_06() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_07() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.OverriddenMethod.IsInitOnly) Assert.NotEmpty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_08() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL1::get_P1() .set instance void CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL1::get_P2() .set instance void CL1::set_P2(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P2(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit CL2 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P1(int32) } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P2(int32) } } .class public auto ansi beforefieldinit CL3 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL3::get_P1() .set instance void CL3::set_P1(int32) } .method public hidebysig virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL3::get_P2() .set instance void CL3::set_P2(int32) } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) Dim cl2p1 = compilation.GetMember(Of PropertySymbol)("CL2.P1") Assert.NotEmpty(cl2p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.OverriddenProperty.TypeCustomModifiers) Dim cl2p2 = compilation.GetMember(Of PropertySymbol)("CL2.P2") Assert.NotEmpty(cl2p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.OverriddenProperty.TypeCustomModifiers) Dim cl3p1 = compilation.GetMember(Of PropertySymbol)("CL3.P1") Assert.Empty(cl3p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.OverriddenProperty.TypeCustomModifiers) Dim cl3p2 = compilation.GetMember(Of PropertySymbol)("CL3.P2") Assert.Empty(cl3p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.OverriddenProperty.TypeCustomModifiers) End Sub <Fact> Public Sub Implementing_01() Dim csSource = " public interface I { int P0 { init; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property P0 As Integer Implements I.P0 Set End Set End Property Public Property P1 As Integer Implements I.P1 End Class Class B2 Implements I Public Property P0 As Integer Implements I.P0 Public ReadOnly Property P1 As Integer Implements I.P1 End Class Class B3 Implements I Public ReadOnly Property P0 As Integer Implements I.P0 Public WriteOnly Property P1 As Integer Implements I.P1 Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public WriteOnly Property P0 As Integer Implements I.P0 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P1 As Integer Implements I.P1 ~~~~ BC31444: 'WriteOnly Property P0 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_02() Dim csSource = " public interface I { int this[int x] { init; } int this[short x] { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item Set End Set End Property Public Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property End Class Class B2 Implements I Public Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property Public ReadOnly Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get End Property End Class Class B3 Implements I Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get End Property Public WriteOnly Property Item(x As Short) As Integer Implements I.Item Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC31444: 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_03() Dim csSource = " public interface I { int P0 { set; get; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B2 Implements I Public Property P0 As Integer Implements I.P0, I.P1 End Class Class B3 Implements I Public Property P0 As Integer Implements I.P1, I.P0 End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0, I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P1, I.P0 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Implementing_04() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.Empty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact()> Public Sub Implementing_05() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.NotEmpty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/56665")> Public Sub LateBound_01() Dim csSource = " public class C { public int P0 { init; get; } public int P1 { init; get; } public int P2 { init; get; } public int P3 { init; get; } private int[] _item = new int[10]; public int this[int x] { init => _item[x] = value; get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox.P0 = -40 b.Init(ox.P1, -41) ob.Init(x.P2, -42) ob.Init(ox.P3, -43) ox(0) = 40 ox.Item(1) = 41 b.Init(ox(2), 42) ob.Init(x(3), 43) b.Init(ox.Item(4), 44) ob.Init(x.Item(5), 45) ob.Init(ox(6), 46) ob.Init(ox.Item(7), 47) System.Console.Write(x.P0) System.Console.Write(" ") System.Console.Write(x.P1) System.Console.Write(" ") System.Console.Write(x.P2) System.Console.Write(" ") System.Console.Write(x.P3) For i as Integer = 0 To 7 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "-40 -41 0 -43 40 41 42 0 44 0 46 47" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/56665")> Public Sub LateBound_02() Dim csSource = " public class C { private int[] _item = new int[12]; public int this[int x] { init => _item[x] = value; get => _item[x]; } public int this[short x] { init => throw null; get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox(0) = 40 ox.Item(1) = 41 x(CObj(2)) = 42 x.Item(CObj(3)) = 43 b.Init(ox(4), 44) ob.Init(ox(5), 45) b.Init(ox.Item(6), 46) ob.Init(ox.Item(7), 47) b.Init(x(CObj(8)), 48) ob.Init(x(CObj(9)), 49) b.Init(x.Item(CObj(10)), 50) ob.Init(x.Item(CObj(11)), 51) System.Console.Write(x(0)) For i as Integer = 1 To 11 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "40 41 42 43 44 45 46 47 48 49 50 51" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub Redim_01() Dim csSource = " public class C { public int[] Property0 { init; get; } public int[] Property1 { init; get; } public int[] Property2 { init; get; } public int[] Property3 { init; get; } public int[] Property4 { init; get; } public int[] Property5 { init; get; } public int[] Property6 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0.Length) System.Console.Write(" "c) System.Console.Write(b.Property3.Length) System.Console.Write(" "c) System.Console.Write(b.Property4.Length) System.Console.Write(" "c) System.Console.Write(b.Property5.Length) System.Console.Write(" "c) System.Console.Write(b.Property6.Length) End Sub End Class Class B Inherits C Public Sub New() ReDim Property0(41) Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me Redim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 45 46 47 48").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Property0(41) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim .Property6(47) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x.Property1(42) With New B() Redim .Property2(43) End With Dim y As New B() With { .F = Sub() ReDim .Property3(44) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Redim .Property4(45) End With With Me With y Redim .Property6(47) End With End With Dim x as New B() Redim x.Property0(41) Dim z = Sub() Redim Property5(46) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Property1(42) ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property2(43) ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property3(44) ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property4(45) ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property6(47) ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim x.Property0(41) ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim Property5(46) ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Property0(41) ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me ReDim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Property0(41) ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property6(47) ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Redim_02() Dim csSource = " public class C { private int[][] _item = new int[6][]; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i).Length) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Item(0)(40) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim .Item(5)(45) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x(0)(40) ReDim x.Item(1)(41) With New B() ReDim .Item(2)(42) End With Dim y As New B() With { .F = Sub() ReDim .Item(3)(43) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y ReDim .Item(4)(44) End With With Me With y ReDim .Item(5)(45) End With End With Dim x as New B() ReDim x(6)(46) ReDim x.Item(7)(47) Dim z = Sub() ReDim Item(8)(48) ReDim Me(9)(49) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(0)(40) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(1)(41) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(2)(42) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(3)(43) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(4)(44) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(6)(46) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(7)(47) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(8)(48) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(9)(49) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(0)(40) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_01() Dim csSource = " public class C { public int[] Property0 { init; get; } = new int[] {}; public int[] Property1 { init; get; } = new int[] {}; public int[] Property2 { init; get; } = new int[] {}; public int[] Property3 { init; get; } = new int[] {}; public int[] Property4 { init; get; } = new int[] {}; public int[] Property5 { init; get; } = new int[] {}; public int[] Property6 { init; get; } = new int[] {}; } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property3 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property4 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property5 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property6 Is Nothing) End Sub End Class Class B Inherits C Public Sub New() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Property0 ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Property6 ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x.Property1 With New B() Erase .Property2 End With Dim y As New B() With { .F = Sub() Erase .Property3 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Property4 End With With Me With y Erase .Property6 End With End With Dim x as New B() Erase x.Property0 Dim z = Sub() Erase Property5 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property1 ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property2 ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property3 ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property4 ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property0 ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property5 ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property0 ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_02() Dim csSource = " public class C { private int[][] _item = new int[6][] {new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}}; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i) Is Nothing) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True True ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Item(0) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Item(5) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x(0) Erase x.Item(1) With New B() Erase .Item(2) End With Dim y As New B() With { .F = Sub() Erase .Item(3) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Item(4) End With With Me With y Erase .Item(5) End With End With Dim x as New B() Erase x(6) Erase x.Item(7) Dim z = Sub() Erase Item(8) Erase Me(9) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(0) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(1) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(2) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(3) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(4) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(6) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(7) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(8) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(9) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(0) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub DictionaryAccess_01() Dim csSource = " public class C { private int[] _item = new int[36]; public int this[string id] { init { int x = int.Parse(id.Substring(1, id.Length - 1)); if (x != 1 && x != 5 && x != 7 && x != 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get { int x = int.Parse(id.Substring(1, id.Length - 1)); return _item[x]; } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b!c9, 49) B.Init((b!c19), 59) With b B.Init(!c11, 51) B.Init((!c21), 61) End With for i as Integer = 0 To 35 System.Console.Write(b("c" & i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Me!c1 = 41 With Me !c5 = 45 End With Init(Me!c7, 47) Init((Me!c23), 63) Dim b = Me Init(b!c12, 52) Init((b!c24), 64) With Me Init(!c8, 48) Init((!c26), 66) End With With b Init(!c14, 54) Init((!c27), 67) End With Test() Dim d = Sub() Init(Me!c34, 74) Init((Me!c35), 75) End Sub d() End Sub Public Sub Test() With Me Init(!c15, 55) Init((!c28), 68) End With Init(Me!c16, 56) Init((Me!c29), 69) Dim b = Me With b Init(!c18, 58) Init((!c31), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="0 41 0 0 0 45 0 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b!c9, 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(!c11, 51) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me!c1 = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. !c5 = 45 ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c7, 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b!c12, 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c8, 48) ~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c14, 54) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c34, 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c15, 55) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c16, 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c18, 58) ~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x!c0 = 40 With New B() !c2 = 42 End With Dim y As New B() With { .F = Sub() !c3 = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y !c4 = 44 End With With Me With y !c5 = 45 End With End With Dim x as New B() x!c6 = 46 Dim z = Sub() Me!c9 = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c0 = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c2 = 42 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c3 = 43 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c4 = 44 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c6 = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c9 = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Me!c1 = 41 With Me !c5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c1 = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnSetAccessorParameter() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Set ~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. c.Property1 = 42 ~~~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetAccessorParameter_AndProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Public Overrides WriteOnly Property Property1 As Integer ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 42 ~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. C.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnInstanceMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig instance void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. c.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. C.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetterOfRefProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property1() { .get instance int32& C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnRefReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property1() .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Dim x2 = c.Property1 ~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnPropertyAndGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 2 ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModOptOnSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modopt(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modopt(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Shared Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Theory, InlineData("Runtime.CompilerServices.IsExternalInit"), InlineData("CompilerServices.IsExternalInit"), InlineData("IsExternalInit"), InlineData("ns.System.Runtime.CompilerServices.IsExternalInit"), InlineData("system.Runtime.CompilerServices.IsExternalInit"), InlineData("System.runtime.CompilerServices.IsExternalInit"), InlineData("System.Runtime.compilerServices.IsExternalInit"), InlineData("System.Runtime.CompilerServices.isExternalInit") > Public Sub IsExternalInitCheck(modifierName As String) Dim ilSource = " .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modreq(" + modifierName + ") set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modreq(" + modifierName + ") C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit " + modifierName + " extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } " Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. c.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub IsInitOnlyValue() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) Dim vbSource2 = <compilation> <file name="c.vb"><![CDATA[ Class Test1(Of T) Public Shared Sub M1() Dim x as Integer = 0 x.DoSomething() End Sub Public Function M2() As System.Action return Sub() End Sub End Function Public Property P As Integer End Class Class Test2 Inherits Test1(Of Integer) End Class Delegate Sub D() Module Ext <System.Runtime.CompilerServices.Extension> Sub DoSomething(x As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilation(vbSource2, references:={compilation1.ToMetadataReference()}, options:=TestOptions.ReleaseDll) Dim tree = compilation2.SyntaxTrees.Single() Dim model = compilation2.GetSemanticModel(tree) Dim lambda = tree.GetRoot.DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(lambda).Symbol, MethodSymbol).IsInitOnly) Dim invocation = tree.GetRoot.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(invocation).Symbol, MethodSymbol).IsInitOnly) Dim verify = Sub(compilation As VisualBasicCompilation) Dim test1 = compilation.GetTypeByMetadataName("Test1`1") Dim p = test1.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim test1Constructed = compilation.GetTypeByMetadataName("Test2").BaseTypeNoUseSiteDiagnostics p = test1Constructed.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim d = compilation.GetTypeByMetadataName("D") For Each m As MethodSymbol In d.GetMembers() Assert.False(m.IsInitOnly) Next End Sub verify(compilation2) Dim compilation3 = CreateCompilation(vbSource1, references:={compilation2.ToMetadataReference()}, options:=TestOptions.ReleaseDll) verify(compilation3) End Sub <Fact> Public Sub ReferenceConversion_01() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_02() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_03() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() TryCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. TryCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_04() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With TryCast(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_05() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() CType(MyBase, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(MyBase, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. CType(MyBase, I1).P1 = 41 ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_06() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(MyClass, I1).P1 = 41 With MyClass .P0 = 1 End With With MyBase .P0 = 2 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. With MyClass ~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. With MyBase ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_07() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Class B Inherits C Public Sub New() Me.P0 = 41 End Sub End Class Class D Public Shared Widening Operator CType(x As D) As B Return Nothing End Operator Public Sub New() CType(Me, B).P0 = 42 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, B).P0 = 42 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_08() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, B).P0 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, B).P0 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_09() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, B) .P0 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P0 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_10() Dim csSource = " public interface I1 { int P1 { get; init; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Structure B Implements I1 Public Sub New(x As Integer) DirectCast(Me, I1).P1 = 41 CType(Me, I1).P1 = 42 DirectCast(CObj(Me), I1).P1 = 43 End Sub End Structure ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC30149: Structure 'B' must implement 'Property P1 As Integer' for interface 'I1'. Implements I1 ~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, I1).P1 = 42 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(CObj(Me), I1).P1 = 43 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CSharp/Portable/Classification/Worker_DocumentationComments.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyDocumentationComment(DocumentationCommentTriviaSyntax documentationComment) { if (!_textSpan.OverlapsWith(documentationComment.Span)) { return; } foreach (var xmlNode in documentationComment.Content) { var childFullSpan = xmlNode.FullSpan; if (childFullSpan.Start > _textSpan.End) { return; } else if (childFullSpan.End < _textSpan.Start) { continue; } ClassifyXmlNode(xmlNode); } // NOTE: the "EndOfComment" token is a special, zero width token. However, if it's a multi-line xml doc comment // the final '*/" will be leading exterior trivia on it. ClassifyXmlTrivia(documentationComment.EndOfComment.LeadingTrivia); } private void ClassifyXmlNode(XmlNodeSyntax node) { switch (node.Kind()) { case SyntaxKind.XmlElement: ClassifyXmlElement((XmlElementSyntax)node); break; case SyntaxKind.XmlEmptyElement: ClassifyXmlEmptyElement((XmlEmptyElementSyntax)node); break; case SyntaxKind.XmlText: ClassifyXmlText((XmlTextSyntax)node); break; case SyntaxKind.XmlComment: ClassifyXmlComment((XmlCommentSyntax)node); break; case SyntaxKind.XmlCDataSection: ClassifyXmlCDataSection((XmlCDataSectionSyntax)node); break; case SyntaxKind.XmlProcessingInstruction: ClassifyXmlProcessingInstruction((XmlProcessingInstructionSyntax)node); break; } } private void ClassifyXmlTrivia(SyntaxTriviaList triviaList) { foreach (var t in triviaList) { switch (t.Kind()) { case SyntaxKind.DocumentationCommentExteriorTrivia: ClassifyExteriorTrivia(t); break; case SyntaxKind.SkippedTokensTrivia: AddClassification(t, ClassificationTypeNames.XmlDocCommentText); break; } } } private void ClassifyExteriorTrivia(SyntaxTrivia trivia) { // Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it. // However, meaningful exterior trivia can also have an undetermined length in the case of // multiline doc comments. // For example: // // /**<summary> // ********* Goo // ******* </summary>*/ // PERFORMANCE: // While the call to SyntaxTrivia.ToString() looks like an allocation, it isn't. // The SyntaxTrivia green node holds the string text of the trivia in a field and ToString() // just returns a reference to that. var text = trivia.ToString(); int? spanStart = null; for (var index = 0; index < text.Length; index++) { var ch = text[index]; if (spanStart != null && char.IsWhiteSpace(ch)) { var span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index); AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter); spanStart = null; } else if (spanStart == null && !char.IsWhiteSpace(ch)) { spanStart = trivia.Span.Start + index; } } // Add a final classification if we hadn't encountered anymore whitespace at the end. if (spanStart != null) { var span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End); AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter); } } private void AddXmlClassification(SyntaxToken token, string classificationType) { if (token.HasLeadingTrivia) ClassifyXmlTrivia(token.LeadingTrivia); AddClassification(token, classificationType); if (token.HasTrailingTrivia) ClassifyXmlTrivia(token.TrailingTrivia); } private void ClassifyXmlTextTokens(SyntaxTokenList textTokens) { foreach (var token in textTokens) { if (token.HasLeadingTrivia) ClassifyXmlTrivia(token.LeadingTrivia); ClassifyXmlTextToken(token); if (token.HasTrailingTrivia) ClassifyXmlTrivia(token.TrailingTrivia); } } private void ClassifyXmlTextToken(SyntaxToken token) { if (token.Kind() == SyntaxKind.XmlEntityLiteralToken) { AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference); } else if (token.Kind() != SyntaxKind.XmlTextLiteralNewLineToken) { RoslynDebug.Assert(token.Parent is object); switch (token.Parent.Kind()) { case SyntaxKind.XmlText: AddClassification(token, ClassificationTypeNames.XmlDocCommentText); break; case SyntaxKind.XmlTextAttribute: AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue); break; case SyntaxKind.XmlComment: AddClassification(token, ClassificationTypeNames.XmlDocCommentComment); break; case SyntaxKind.XmlCDataSection: AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection); break; case SyntaxKind.XmlProcessingInstruction: AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction); break; } } } private void ClassifyXmlName(XmlNameSyntax node) { var classificationType = node.Parent switch { XmlAttributeSyntax => ClassificationTypeNames.XmlDocCommentAttributeName, XmlProcessingInstructionSyntax => ClassificationTypeNames.XmlDocCommentProcessingInstruction, _ => ClassificationTypeNames.XmlDocCommentName, }; var prefix = node.Prefix; if (prefix != null) { AddXmlClassification(prefix.Prefix, classificationType); AddXmlClassification(prefix.ColonToken, classificationType); } AddXmlClassification(node.LocalName, classificationType); } private void ClassifyXmlElement(XmlElementSyntax node) { ClassifyXmlElementStartTag(node.StartTag); foreach (var xmlNode in node.Content) { ClassifyXmlNode(xmlNode); } ClassifyXmlElementEndTag(node.EndTag); } private void ClassifyXmlElementStartTag(XmlElementStartTagSyntax node) { AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); foreach (var attribute in node.Attributes) { ClassifyXmlAttribute(attribute); } AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlElementEndTag(XmlElementEndTagSyntax node) { AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlEmptyElement(XmlEmptyElementSyntax node) { AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); foreach (var attribute in node.Attributes) { ClassifyXmlAttribute(attribute); } AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlAttribute(XmlAttributeSyntax attribute) { ClassifyXmlName(attribute.Name); AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter); AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes); switch (attribute.Kind()) { case SyntaxKind.XmlTextAttribute: ClassifyXmlTextTokens(((XmlTextAttributeSyntax)attribute).TextTokens); break; case SyntaxKind.XmlCrefAttribute: ClassifyNode(((XmlCrefAttributeSyntax)attribute).Cref); break; case SyntaxKind.XmlNameAttribute: ClassifyNode(((XmlNameAttributeSyntax)attribute).Identifier); break; } AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes); } private void ClassifyXmlText(XmlTextSyntax node) => ClassifyXmlTextTokens(node.TextTokens); private void ClassifyXmlComment(XmlCommentSyntax node) { AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlCDataSection(XmlCDataSectionSyntax node) { AddXmlClassification(node.StartCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlProcessingInstruction(XmlProcessingInstructionSyntax node) { AddXmlClassification(node.StartProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction); ClassifyXmlName(node.Name); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.EndProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyDocumentationComment(DocumentationCommentTriviaSyntax documentationComment) { if (!_textSpan.OverlapsWith(documentationComment.Span)) { return; } foreach (var xmlNode in documentationComment.Content) { var childFullSpan = xmlNode.FullSpan; if (childFullSpan.Start > _textSpan.End) { return; } else if (childFullSpan.End < _textSpan.Start) { continue; } ClassifyXmlNode(xmlNode); } // NOTE: the "EndOfComment" token is a special, zero width token. However, if it's a multi-line xml doc comment // the final '*/" will be leading exterior trivia on it. ClassifyXmlTrivia(documentationComment.EndOfComment.LeadingTrivia); } private void ClassifyXmlNode(XmlNodeSyntax node) { switch (node.Kind()) { case SyntaxKind.XmlElement: ClassifyXmlElement((XmlElementSyntax)node); break; case SyntaxKind.XmlEmptyElement: ClassifyXmlEmptyElement((XmlEmptyElementSyntax)node); break; case SyntaxKind.XmlText: ClassifyXmlText((XmlTextSyntax)node); break; case SyntaxKind.XmlComment: ClassifyXmlComment((XmlCommentSyntax)node); break; case SyntaxKind.XmlCDataSection: ClassifyXmlCDataSection((XmlCDataSectionSyntax)node); break; case SyntaxKind.XmlProcessingInstruction: ClassifyXmlProcessingInstruction((XmlProcessingInstructionSyntax)node); break; } } private void ClassifyXmlTrivia(SyntaxTriviaList triviaList) { foreach (var t in triviaList) { switch (t.Kind()) { case SyntaxKind.DocumentationCommentExteriorTrivia: ClassifyExteriorTrivia(t); break; case SyntaxKind.SkippedTokensTrivia: AddClassification(t, ClassificationTypeNames.XmlDocCommentText); break; } } } private void ClassifyExteriorTrivia(SyntaxTrivia trivia) { // Note: The exterior trivia can contain whitespace (usually leading) and we want to avoid classifying it. // However, meaningful exterior trivia can also have an undetermined length in the case of // multiline doc comments. // For example: // // /**<summary> // ********* Goo // ******* </summary>*/ // PERFORMANCE: // While the call to SyntaxTrivia.ToString() looks like an allocation, it isn't. // The SyntaxTrivia green node holds the string text of the trivia in a field and ToString() // just returns a reference to that. var text = trivia.ToString(); int? spanStart = null; for (var index = 0; index < text.Length; index++) { var ch = text[index]; if (spanStart != null && char.IsWhiteSpace(ch)) { var span = TextSpan.FromBounds(spanStart.Value, spanStart.Value + index); AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter); spanStart = null; } else if (spanStart == null && !char.IsWhiteSpace(ch)) { spanStart = trivia.Span.Start + index; } } // Add a final classification if we hadn't encountered anymore whitespace at the end. if (spanStart != null) { var span = TextSpan.FromBounds(spanStart.Value, trivia.Span.End); AddClassification(span, ClassificationTypeNames.XmlDocCommentDelimiter); } } private void AddXmlClassification(SyntaxToken token, string classificationType) { if (token.HasLeadingTrivia) ClassifyXmlTrivia(token.LeadingTrivia); AddClassification(token, classificationType); if (token.HasTrailingTrivia) ClassifyXmlTrivia(token.TrailingTrivia); } private void ClassifyXmlTextTokens(SyntaxTokenList textTokens) { foreach (var token in textTokens) { if (token.HasLeadingTrivia) ClassifyXmlTrivia(token.LeadingTrivia); ClassifyXmlTextToken(token); if (token.HasTrailingTrivia) ClassifyXmlTrivia(token.TrailingTrivia); } } private void ClassifyXmlTextToken(SyntaxToken token) { if (token.Kind() == SyntaxKind.XmlEntityLiteralToken) { AddClassification(token, ClassificationTypeNames.XmlDocCommentEntityReference); } else if (token.Kind() != SyntaxKind.XmlTextLiteralNewLineToken) { RoslynDebug.Assert(token.Parent is object); switch (token.Parent.Kind()) { case SyntaxKind.XmlText: AddClassification(token, ClassificationTypeNames.XmlDocCommentText); break; case SyntaxKind.XmlTextAttribute: AddClassification(token, ClassificationTypeNames.XmlDocCommentAttributeValue); break; case SyntaxKind.XmlComment: AddClassification(token, ClassificationTypeNames.XmlDocCommentComment); break; case SyntaxKind.XmlCDataSection: AddClassification(token, ClassificationTypeNames.XmlDocCommentCDataSection); break; case SyntaxKind.XmlProcessingInstruction: AddClassification(token, ClassificationTypeNames.XmlDocCommentProcessingInstruction); break; } } } private void ClassifyXmlName(XmlNameSyntax node) { var classificationType = node.Parent switch { XmlAttributeSyntax => ClassificationTypeNames.XmlDocCommentAttributeName, XmlProcessingInstructionSyntax => ClassificationTypeNames.XmlDocCommentProcessingInstruction, _ => ClassificationTypeNames.XmlDocCommentName, }; var prefix = node.Prefix; if (prefix != null) { AddXmlClassification(prefix.Prefix, classificationType); AddXmlClassification(prefix.ColonToken, classificationType); } AddXmlClassification(node.LocalName, classificationType); } private void ClassifyXmlElement(XmlElementSyntax node) { ClassifyXmlElementStartTag(node.StartTag); foreach (var xmlNode in node.Content) { ClassifyXmlNode(xmlNode); } ClassifyXmlElementEndTag(node.EndTag); } private void ClassifyXmlElementStartTag(XmlElementStartTagSyntax node) { AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); foreach (var attribute in node.Attributes) { ClassifyXmlAttribute(attribute); } AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlElementEndTag(XmlElementEndTagSyntax node) { AddXmlClassification(node.LessThanSlashToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); AddXmlClassification(node.GreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlEmptyElement(XmlEmptyElementSyntax node) { AddXmlClassification(node.LessThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlName(node.Name); foreach (var attribute in node.Attributes) { ClassifyXmlAttribute(attribute); } AddXmlClassification(node.SlashGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlAttribute(XmlAttributeSyntax attribute) { ClassifyXmlName(attribute.Name); AddXmlClassification(attribute.EqualsToken, ClassificationTypeNames.XmlDocCommentDelimiter); AddXmlClassification(attribute.StartQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes); switch (attribute.Kind()) { case SyntaxKind.XmlTextAttribute: ClassifyXmlTextTokens(((XmlTextAttributeSyntax)attribute).TextTokens); break; case SyntaxKind.XmlCrefAttribute: ClassifyNode(((XmlCrefAttributeSyntax)attribute).Cref); break; case SyntaxKind.XmlNameAttribute: ClassifyNode(((XmlNameAttributeSyntax)attribute).Identifier); break; } AddXmlClassification(attribute.EndQuoteToken, ClassificationTypeNames.XmlDocCommentAttributeQuotes); } private void ClassifyXmlText(XmlTextSyntax node) => ClassifyXmlTextTokens(node.TextTokens); private void ClassifyXmlComment(XmlCommentSyntax node) { AddXmlClassification(node.LessThanExclamationMinusMinusToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.MinusMinusGreaterThanToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlCDataSection(XmlCDataSectionSyntax node) { AddXmlClassification(node.StartCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.EndCDataToken, ClassificationTypeNames.XmlDocCommentDelimiter); } private void ClassifyXmlProcessingInstruction(XmlProcessingInstructionSyntax node) { AddXmlClassification(node.StartProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction); ClassifyXmlName(node.Name); ClassifyXmlTextTokens(node.TextTokens); AddXmlClassification(node.EndProcessingInstructionToken, ClassificationTypeNames.XmlDocCommentProcessingInstruction); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller.Session_UpdateModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session { internal struct SignatureHelpSelection { private readonly SignatureHelpItem _selectedItem; private readonly bool _userSelected; private readonly int? _selectedParameter; public SignatureHelpSelection(SignatureHelpItem selectedItem, bool userSelected, int? selectedParameter) : this() { _selectedItem = selectedItem; _userSelected = userSelected; _selectedParameter = selectedParameter; } public int? SelectedParameter => _selectedParameter; public SignatureHelpItem SelectedItem => _selectedItem; public bool UserSelected => _userSelected; } internal static class DefaultSignatureHelpSelector { public static SignatureHelpSelection GetSelection( IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, bool userSelected, int argumentIndex, int argumentCount, string argumentName, bool isCaseSensitive) { SelectBestItem(ref selectedItem, ref userSelected, items, argumentIndex, argumentCount, argumentName, isCaseSensitive); var selectedParameter = GetSelectedParameter(selectedItem, argumentIndex, argumentName, isCaseSensitive); return new SignatureHelpSelection(selectedItem, userSelected, selectedParameter); } private static int GetSelectedParameter(SignatureHelpItem bestItem, int parameterIndex, string parameterName, bool isCaseSensitive) { if (!string.IsNullOrEmpty(parameterName)) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var index = bestItem.Parameters.IndexOf(p => comparer.Equals(p.Name, parameterName)); if (index >= 0) { return index; } } return parameterIndex; } private static void SelectBestItem(ref SignatureHelpItem currentItem, ref bool userSelected, IList<SignatureHelpItem> filteredItems, int selectedParameter, int argumentCount, string name, bool isCaseSensitive) { // If the current item is still applicable, then just keep it. if (filteredItems.Contains(currentItem) && IsApplicable(currentItem, argumentCount, name, isCaseSensitive)) { // If the current item was user-selected, we keep it as such. return; } // If the current item is no longer applicable, we'll be choosing a new one, // which was definitely not previously user-selected. userSelected = false; // Try to find the first applicable item. If there is none, then that means the // selected parameter was outside the bounds of all methods. i.e. all methods only // went up to 3 parameters, and selected parameter is 3 or higher. In that case, // just pick the very last item as it is closest in parameter count. var result = filteredItems.FirstOrDefault(i => IsApplicable(i, argumentCount, name, isCaseSensitive)); if (result != null) { currentItem = result; return; } // if we couldn't find a best item, and they provided a name, then try again without // a name. if (name != null) { SelectBestItem(ref currentItem, ref userSelected, filteredItems, selectedParameter, argumentCount, null, isCaseSensitive); return; } // If we don't have an item that can take that number of parameters, then just pick // the last item. Or stick with the current item if the last item isn't any better. var lastItem = filteredItems.Last(); if (currentItem.IsVariadic || currentItem.Parameters.Length == lastItem.Parameters.Length) { return; } currentItem = lastItem; } private static bool IsApplicable(SignatureHelpItem item, int argumentCount, string name, bool isCaseSensitive) { // If they provided a name, then the item is only valid if it has a parameter that // matches that name. if (name != null) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; return item.Parameters.Any(p => comparer.Equals(p.Name, name)); } // An item is applicable if it has at least as many parameters as the selected // parameter index. i.e. if it has 2 parameters and we're at index 0 or 1 then it's // applicable. However, if it has 2 parameters and we're at index 2, then it's not // applicable. if (item.Parameters.Length >= argumentCount) { return true; } // However, if it is variadic then it is applicable as it can take any number of // items. if (item.IsVariadic) { return true; } // Also, we special case 0. that's because if the user has "Goo(" and goo takes no // arguments, then we'll see that it's arg count is 0. We still want to consider // any item applicable here though. return argumentCount == 0; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session { internal struct SignatureHelpSelection { private readonly SignatureHelpItem _selectedItem; private readonly bool _userSelected; private readonly int? _selectedParameter; public SignatureHelpSelection(SignatureHelpItem selectedItem, bool userSelected, int? selectedParameter) : this() { _selectedItem = selectedItem; _userSelected = userSelected; _selectedParameter = selectedParameter; } public int? SelectedParameter => _selectedParameter; public SignatureHelpItem SelectedItem => _selectedItem; public bool UserSelected => _userSelected; } internal static class DefaultSignatureHelpSelector { public static SignatureHelpSelection GetSelection( IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, bool userSelected, int argumentIndex, int argumentCount, string argumentName, bool isCaseSensitive) { SelectBestItem(ref selectedItem, ref userSelected, items, argumentIndex, argumentCount, argumentName, isCaseSensitive); var selectedParameter = GetSelectedParameter(selectedItem, argumentIndex, argumentName, isCaseSensitive); return new SignatureHelpSelection(selectedItem, userSelected, selectedParameter); } private static int GetSelectedParameter(SignatureHelpItem bestItem, int parameterIndex, string parameterName, bool isCaseSensitive) { if (!string.IsNullOrEmpty(parameterName)) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var index = bestItem.Parameters.IndexOf(p => comparer.Equals(p.Name, parameterName)); if (index >= 0) { return index; } } return parameterIndex; } private static void SelectBestItem(ref SignatureHelpItem currentItem, ref bool userSelected, IList<SignatureHelpItem> filteredItems, int selectedParameter, int argumentCount, string name, bool isCaseSensitive) { // If the current item is still applicable, then just keep it. if (filteredItems.Contains(currentItem) && IsApplicable(currentItem, argumentCount, name, isCaseSensitive)) { // If the current item was user-selected, we keep it as such. return; } // If the current item is no longer applicable, we'll be choosing a new one, // which was definitely not previously user-selected. userSelected = false; // Try to find the first applicable item. If there is none, then that means the // selected parameter was outside the bounds of all methods. i.e. all methods only // went up to 3 parameters, and selected parameter is 3 or higher. In that case, // just pick the very last item as it is closest in parameter count. var result = filteredItems.FirstOrDefault(i => IsApplicable(i, argumentCount, name, isCaseSensitive)); if (result != null) { currentItem = result; return; } // if we couldn't find a best item, and they provided a name, then try again without // a name. if (name != null) { SelectBestItem(ref currentItem, ref userSelected, filteredItems, selectedParameter, argumentCount, null, isCaseSensitive); return; } // If we don't have an item that can take that number of parameters, then just pick // the last item. Or stick with the current item if the last item isn't any better. var lastItem = filteredItems.Last(); if (currentItem.IsVariadic || currentItem.Parameters.Length == lastItem.Parameters.Length) { return; } currentItem = lastItem; } private static bool IsApplicable(SignatureHelpItem item, int argumentCount, string name, bool isCaseSensitive) { // If they provided a name, then the item is only valid if it has a parameter that // matches that name. if (name != null) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; return item.Parameters.Any(p => comparer.Equals(p.Name, name)); } // An item is applicable if it has at least as many parameters as the selected // parameter index. i.e. if it has 2 parameters and we're at index 0 or 1 then it's // applicable. However, if it has 2 parameters and we're at index 2, then it's not // applicable. if (item.Parameters.Length >= argumentCount) { return true; } // However, if it is variadic then it is applicable as it can take any number of // items. if (item.IsVariadic) { return true; } // Also, we special case 0. that's because if the user has "Goo(" and goo takes no // arguments, then we'll see that it's arg count is 0. We still want to consider // any item applicable here though. return argumentCount == 0; } } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/CSharp/Impl/ObjectBrowser/ObjectBrowserLibraryManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager { public ObjectBrowserLibraryManager( IServiceProvider serviceProvider, IComponentModel componentModel, VisualStudioWorkspace workspace) : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace) { } internal override AbstractDescriptionBuilder CreateDescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectListItem listItem, Project project) { return new DescriptionBuilder(description, this, listItem, project); } internal override AbstractListItemFactory CreateListItemFactory() => new ListItemFactory(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager { public ObjectBrowserLibraryManager( IServiceProvider serviceProvider, IComponentModel componentModel, VisualStudioWorkspace workspace) : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace) { } internal override AbstractDescriptionBuilder CreateDescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectListItem listItem, Project project) { return new DescriptionBuilder(description, this, listItem, project); } internal override AbstractListItemFactory CreateListItemFactory() => new ListItemFactory(); } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.InvocationLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { #region Methods [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInParameterList() { var markup = @" using System; class MyClass { public void Goo(int x, $$string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeAfterParameterList() { var markup = @" using System; class MyClass { public void Goo(int x, string y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodDeclaration() { var markup = @" using System; class MyClass { $$public void Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToSt$$ring(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { $$((System.IFormattable)null).ToString(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToString(""test"",$$ null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() { var markup = @" class C { string s = ((System.IFormattable)null).ToString(""test"", null)$$; }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaCommand() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$ } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, expectedSuccess: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaSmartTag() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { [||] } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_ArgumentList() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls1() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar($$Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(Baz(y, x), y); } public void Bar(int x, string y) { } public int Baz(string y, int x) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls2() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar$$(Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls3() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar(Baz(x, y), $$y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_Attribute() { var markup = @" using System; [$$My(1, 2)] class MyAttribute : Attribute { public MyAttribute(int x, int y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; [My(2, 1)] class MyAttribute : Attribute { public MyAttribute(int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { var markup = @" class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M(""s"", 1); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, ""s""); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { var markup = @" class Program { public Program(int x, int y) : this(1, 2, 3)$$ { } public Program(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { public Program(int x, int y) : this(3, 2, 1) { } public Program(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { var markup = @" class B { public B(int a, int b) { } } class D : B { public D(int x, int y) : base(1, 2)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public B(int b, int a) { } } class D : B { public D(int x, int y) : base(2, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Indexers [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { var markup = @" class Program { $$int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InParameters() { var markup = @" class Program { int this[int x, $$string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtEndOfDeclaration() { var markup = @" class Program { int this[int x, string y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeInAccessor() { var markup = @" class Program { int this[int x, string y] { get { return $$5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { var markup = @" class Program { void M(Program p) { var t = $$p[5, ""test""]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_InArgumentList() { var markup = @" class Program { void M(Program p) { var t = p[5, ""test""$$]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } #endregion #region Delegates [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation1() { var markup = @" public class C { void T() { var d = new $$D((x, y) => { }); } public delegate void D(int x, int y); }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class C { void T() { var d = new D((y, x) => { }); } public delegate void D(int y, int x); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation2() { var markup = @" public class CD<T> { public delegate void D(T t, T u); } class Test { public void M() { var dele = new CD<int>.$$D((int x, int y) => { }); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class CD<T> { public delegate void D(T u, T t); } class Test { public void M() { var dele = new CD<int>.D((int y, int x) => { }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region CodeRefactoring [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void [||]Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { [||] } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InLambda() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b)[||] => { return a; }; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int x) { System.Func<int, int, int> f = (b, a) => { return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b) => { [||]return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCommand() { var markup = @" class Program { void M(int x, int y) { M($$5, 6); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int y, int x) { M(6, 5); } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCodeAction() { var markup = @" class Program { void M(int x, int y) { M([||]5, 6); } }"; await TestMissingAsync(markup); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { #region Methods [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void $$Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInParameterList() { var markup = @" using System; class MyClass { public void Goo(int x, $$string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeAfterParameterList() { var markup = @" using System; class MyClass { public void Goo(int x, string y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodDeclaration() { var markup = @" using System; class MyClass { $$public void Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToSt$$ring(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { $$((System.IFormattable)null).ToString(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToString(""test"",$$ null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.DefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() { var markup = @" class C { string s = ((System.IFormattable)null).ToString(""test"", null)$$; }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedFailureReason: ChangeSignatureFailureKind.IncorrectKind); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaCommand() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$ } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, expectedSuccess: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody_ViaSmartTag() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { [||] } }"; await TestMissingAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_ArgumentList() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls1() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar($$Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(Baz(y, x), y); } public void Bar(int x, string y) { } public int Baz(string y, int x) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls2() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar$$(Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls3() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { Bar(Baz(x, y), $$y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_Attribute() { var markup = @" using System; [$$My(1, 2)] class MyAttribute : Attribute { public MyAttribute(int x, int y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; [My(2, 1)] class MyAttribute : Attribute { public MyAttribute(int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { var markup = @" class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M(""s"", 1); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, ""s""); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { var markup = @" class Program { public Program(int x, int y) : this(1, 2, 3)$$ { } public Program(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { public Program(int x, int y) : this(3, 2, 1) { } public Program(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { var markup = @" class B { public B(int a, int b) { } } class D : B { public D(int x, int y) : base(1, 2)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public B(int b, int a) { } } class D : B { public D(int x, int y) : base(2, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Indexers [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { var markup = @" class Program { $$int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InParameters() { var markup = @" class Program { int this[int x, $$string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 1); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtEndOfDeclaration() { var markup = @" class Program { int this[int x, string y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeInAccessor() { var markup = @" class Program { int this[int x, string y] { get { return $$5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { var markup = @" class Program { void M(Program p) { var t = $$p[5, ""test""]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_InArgumentList() { var markup = @" class Program { void M(Program p) { var t = p[5, ""test""$$]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } #endregion #region Delegates [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation1() { var markup = @" public class C { void T() { var d = new $$D((x, y) => { }); } public delegate void D(int x, int y); }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class C { void T() { var d = new D((y, x) => { }); } public delegate void D(int y, int x); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode, expectedSelectedIndex: 0); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation2() { var markup = @" public class CD<T> { public delegate void D(T t, T u); } class Test { public void M() { var dele = new CD<int>.$$D((int x, int y) => { }); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class CD<T> { public delegate void D(T u, T t); } class Test { public void M() { var dele = new CD<int>.D((int y, int x) => { }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region CodeRefactoring [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void [||]Goo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Goo(string y, int x) { } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() { var markup = @" using System; class MyClass { public void Goo(int x, string y) { [||] } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InLambda() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b)[||] => { return a; }; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int x) { System.Func<int, int, int> f = (b, a) => { return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b) => { [||]return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCommand() { var markup = @" class Program { void M(int x, int y) { M($$5, 6); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int y, int x) { M(6, 5); } }"; await TestChangeSignatureViaCommandAsync( LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite_ViaCodeAction() { var markup = @" class Program { void M(int x, int y) { M([||]5, 6); } }"; await TestMissingAsync(markup); } #endregion } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/CSharp/Portable/EmbeddedLanguages/LanguageServices/CSharpEmbeddedLanguagesProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.LanguageServices { [ExportLanguageService(typeof(IEmbeddedLanguagesProvider), LanguageNames.CSharp, ServiceLayer.Default), Shared] internal class CSharpEmbeddedLanguagesProvider : AbstractEmbeddedLanguagesProvider { public static EmbeddedLanguageInfo Info = new( (int)SyntaxKind.CharacterLiteralToken, (int)SyntaxKind.StringLiteralToken, (int)SyntaxKind.InterpolatedStringTextToken, CSharpSyntaxFacts.Instance, CSharpSemanticFactsService.Instance, CSharpVirtualCharService.Instance); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEmbeddedLanguagesProvider() : base(Info) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages.LanguageServices { [ExportLanguageService(typeof(IEmbeddedLanguagesProvider), LanguageNames.CSharp, ServiceLayer.Default), Shared] internal class CSharpEmbeddedLanguagesProvider : AbstractEmbeddedLanguagesProvider { public static EmbeddedLanguageInfo Info = new( (int)SyntaxKind.CharacterLiteralToken, (int)SyntaxKind.StringLiteralToken, (int)SyntaxKind.InterpolatedStringTextToken, CSharpSyntaxFacts.Instance, CSharpSemanticFactsService.Instance, CSharpVirtualCharService.Instance); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEmbeddedLanguagesProvider() : base(Info) { } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/Symbols/AbstractTypeMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Abstract base class for mutable and immutable type maps. /// </summary> internal abstract class AbstractTypeMap { /// <summary> /// Substitute for a type declaration. May use alpha renaming if the container is substituted. /// </summary> internal virtual NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) { Debug.Assert((object)previous.ConstructedFrom == (object)previous); NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType); if ((object)newContainingType == null) { return previous; } return previous.OriginalDefinition.AsMember(newContainingType); } /// <summary> /// SubstType, but for NamedTypeSymbols only. This is used for concrete types, so no alpha substitution appears in the result. /// </summary> internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous) { if (ReferenceEquals(previous, null)) return null; if (previous.IsUnboundGenericType) return previous; if (previous.IsAnonymousType) { ImmutableArray<TypeWithAnnotations> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(previous); ImmutableArray<TypeWithAnnotations> newFieldTypes = SubstituteTypes(oldFieldTypes); return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes); } // TODO: we could construct the result's ConstructedFrom lazily by using a "deep" // construct operation here (as VB does), thereby avoiding alpha renaming in most cases. // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common. NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom; NamedTypeSymbol newConstructedFrom = SubstituteTypeDeclaration(oldConstructedFrom); ImmutableArray<TypeWithAnnotations> oldTypeArguments = previous.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; bool changed = !ReferenceEquals(oldConstructedFrom, newConstructedFrom); var newTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldTypeArguments.Length); for (int i = 0; i < oldTypeArguments.Length; i++) { var oldArgument = oldTypeArguments[i]; var newArgument = oldArgument.SubstituteType(this); if (!changed && !oldArgument.IsSameAs(newArgument)) { changed = true; } newTypeArguments.Add(newArgument); } if (!changed) { newTypeArguments.Free(); return previous; } return newConstructedFrom.ConstructIfGeneric(newTypeArguments.ToImmutableAndFree()).WithTupleDataFrom(previous); } /// <summary> /// Perform the substitution on the given type. Each occurrence of the type parameter is /// replaced with its corresponding type argument from the map. /// </summary> /// <param name="previous">The type to be rewritten.</param> /// <returns>The type with type parameters replaced with the type arguments.</returns> internal TypeWithAnnotations SubstituteType(TypeSymbol previous) { if (ReferenceEquals(previous, null)) return default(TypeWithAnnotations); TypeSymbol result; switch (previous.Kind) { case SymbolKind.NamedType: result = SubstituteNamedType((NamedTypeSymbol)previous); break; case SymbolKind.TypeParameter: return SubstituteTypeParameter((TypeParameterSymbol)previous); case SymbolKind.ArrayType: result = SubstituteArrayType((ArrayTypeSymbol)previous); break; case SymbolKind.PointerType: result = SubstitutePointerType((PointerTypeSymbol)previous); break; case SymbolKind.FunctionPointerType: result = SubstituteFunctionPointerType((FunctionPointerTypeSymbol)previous); break; case SymbolKind.DynamicType: result = SubstituteDynamicType(); break; case SymbolKind.ErrorType: return ((ErrorTypeSymbol)previous).Substitute(this); default: result = previous; break; } return TypeWithAnnotations.Create(result); } internal TypeWithAnnotations SubstituteType(TypeWithAnnotations previous) { return previous.SubstituteType(this); } internal virtual ImmutableArray<CustomModifier> SubstituteCustomModifiers(ImmutableArray<CustomModifier> customModifiers) { if (customModifiers.IsDefaultOrEmpty) { return customModifiers; } for (int i = 0; i < customModifiers.Length; i++) { NamedTypeSymbol modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; var substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { var builder = ArrayBuilder<CustomModifier>.GetInstance(customModifiers.Length); builder.AddRange(customModifiers, i); builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); for (i++; i < customModifiers.Length; i++) { modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); } else { builder.Add(customModifiers[i]); } } Debug.Assert(builder.Count == customModifiers.Length); return builder.ToImmutableAndFree(); } } return customModifiers; } protected virtual TypeSymbol SubstituteDynamicType() { return DynamicTypeSymbol.Instance; } protected virtual TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) { return TypeWithAnnotations.Create(typeParameter); } private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t) { var oldElement = t.ElementTypeWithAnnotations; TypeWithAnnotations element = oldElement.SubstituteType(this); if (element.IsSameAs(oldElement)) { return t; } if (t.IsSZArray) { ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics(); Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2); if (interfaces.Length == 1) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0])); } else if (interfaces.Length == 2) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0]), SubstituteNamedType(interfaces[1])); } else if (interfaces.Length != 0) { throw ExceptionUtilities.Unreachable; } return ArrayTypeSymbol.CreateSZArray( element, t.BaseTypeNoUseSiteDiagnostics, interfaces); } return ArrayTypeSymbol.CreateMDArray( element, t.Rank, t.Sizes, t.LowerBounds, t.BaseTypeNoUseSiteDiagnostics); } private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t) { var oldPointedAtType = t.PointedAtTypeWithAnnotations; var pointedAtType = oldPointedAtType.SubstituteType(this); if (pointedAtType.IsSameAs(oldPointedAtType)) { return t; } return new PointerTypeSymbol(pointedAtType); } private FunctionPointerTypeSymbol SubstituteFunctionPointerType(FunctionPointerTypeSymbol f) { var substitutedReturnType = f.Signature.ReturnTypeWithAnnotations.SubstituteType(this); var refCustomModifiers = f.Signature.RefCustomModifiers; var substitutedRefCustomModifiers = SubstituteCustomModifiers(refCustomModifiers); var parameterTypesWithAnnotations = f.Signature.ParameterTypesWithAnnotations; ImmutableArray<TypeWithAnnotations> substitutedParamTypes = SubstituteTypes(parameterTypesWithAnnotations); ImmutableArray<ImmutableArray<CustomModifier>> substitutedParamModifiers = default; var paramCount = f.Signature.Parameters.Length; if (paramCount > 0) { var builder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool didSubstitute = false; foreach (var param in f.Signature.Parameters) { var substituted = SubstituteCustomModifiers(param.RefCustomModifiers); builder.Add(substituted); if (substituted != param.RefCustomModifiers) { didSubstitute = true; } } if (didSubstitute) { substitutedParamModifiers = builder.ToImmutableAndFree(); } else { builder.Free(); } } if (substitutedParamTypes != parameterTypesWithAnnotations || !substitutedParamModifiers.IsDefault || !f.Signature.ReturnTypeWithAnnotations.IsSameAs(substitutedReturnType) || substitutedRefCustomModifiers != refCustomModifiers) { f = f.SubstituteTypeSymbol(substitutedReturnType, substitutedParamTypes, refCustomModifiers, substitutedParamModifiers); } return f; } internal ImmutableArray<TypeSymbol> SubstituteTypesWithoutModifiers(ImmutableArray<TypeSymbol> original) { if (original.IsDefault) { return original; } TypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteType(t).Type; if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new TypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } internal ImmutableArray<TypeWithAnnotations> SubstituteTypes(ImmutableArray<TypeWithAnnotations> original) { if (original.IsDefault) { return default(ImmutableArray<TypeWithAnnotations>); } var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(original.Length); foreach (TypeWithAnnotations t in original) { result.Add(SubstituteType(t)); } return result.ToImmutableAndFree(); } /// <summary> /// Substitute types, and return the results without duplicates, preserving the original order. /// Note, all occurrences of 'dynamic' in resulting types will be replaced with 'object'. /// </summary> internal void SubstituteConstraintTypesDistinctWithoutModifiers( TypeParameterSymbol owner, ImmutableArray<TypeWithAnnotations> original, ArrayBuilder<TypeWithAnnotations> result, HashSet<TypeParameterSymbol> ignoreTypesDependentOnTypeParametersOpt) { DynamicTypeEraser dynamicEraser = null; if (original.Length == 0) { return; } else if (original.Length == 1) { var type = original[0]; if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { result.Add(substituteConstraintType(type)); } } else { var map = PooledDictionary<TypeSymbol, int>.GetInstance(); foreach (var type in original) { if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { var substituted = substituteConstraintType(type); if (!map.TryGetValue(substituted.Type, out int mergeWith)) { map.Add(substituted.Type, result.Count); result.Add(substituted); } else { result[mergeWith] = ConstraintsHelper.ConstraintWithMostSignificantNullability(result[mergeWith], substituted); } } } map.Free(); } TypeWithAnnotations substituteConstraintType(TypeWithAnnotations type) { if (dynamicEraser == null) { dynamicEraser = new DynamicTypeEraser(owner.ContainingAssembly.CorLibrary.GetSpecialType(SpecialType.System_Object)); } TypeWithAnnotations substituted = SubstituteType(type); return substituted.WithTypeAndModifiers(dynamicEraser.EraseDynamic(substituted.Type), substituted.CustomModifiers); } } internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original) { return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp).AsTypeSymbolOnly(), this); } /// <summary> /// Like SubstTypes, but for NamedTypeSymbols. /// </summary> internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original) { NamedTypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteNamedType(t); if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new NamedTypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Abstract base class for mutable and immutable type maps. /// </summary> internal abstract class AbstractTypeMap { /// <summary> /// Substitute for a type declaration. May use alpha renaming if the container is substituted. /// </summary> internal virtual NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) { Debug.Assert((object)previous.ConstructedFrom == (object)previous); NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType); if ((object)newContainingType == null) { return previous; } return previous.OriginalDefinition.AsMember(newContainingType); } /// <summary> /// SubstType, but for NamedTypeSymbols only. This is used for concrete types, so no alpha substitution appears in the result. /// </summary> internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous) { if (ReferenceEquals(previous, null)) return null; if (previous.IsUnboundGenericType) return previous; if (previous.IsAnonymousType) { ImmutableArray<TypeWithAnnotations> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(previous); ImmutableArray<TypeWithAnnotations> newFieldTypes = SubstituteTypes(oldFieldTypes); return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes); } // TODO: we could construct the result's ConstructedFrom lazily by using a "deep" // construct operation here (as VB does), thereby avoiding alpha renaming in most cases. // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common. NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom; NamedTypeSymbol newConstructedFrom = SubstituteTypeDeclaration(oldConstructedFrom); ImmutableArray<TypeWithAnnotations> oldTypeArguments = previous.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; bool changed = !ReferenceEquals(oldConstructedFrom, newConstructedFrom); var newTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldTypeArguments.Length); for (int i = 0; i < oldTypeArguments.Length; i++) { var oldArgument = oldTypeArguments[i]; var newArgument = oldArgument.SubstituteType(this); if (!changed && !oldArgument.IsSameAs(newArgument)) { changed = true; } newTypeArguments.Add(newArgument); } if (!changed) { newTypeArguments.Free(); return previous; } return newConstructedFrom.ConstructIfGeneric(newTypeArguments.ToImmutableAndFree()).WithTupleDataFrom(previous); } /// <summary> /// Perform the substitution on the given type. Each occurrence of the type parameter is /// replaced with its corresponding type argument from the map. /// </summary> /// <param name="previous">The type to be rewritten.</param> /// <returns>The type with type parameters replaced with the type arguments.</returns> internal TypeWithAnnotations SubstituteType(TypeSymbol previous) { if (ReferenceEquals(previous, null)) return default(TypeWithAnnotations); TypeSymbol result; switch (previous.Kind) { case SymbolKind.NamedType: result = SubstituteNamedType((NamedTypeSymbol)previous); break; case SymbolKind.TypeParameter: return SubstituteTypeParameter((TypeParameterSymbol)previous); case SymbolKind.ArrayType: result = SubstituteArrayType((ArrayTypeSymbol)previous); break; case SymbolKind.PointerType: result = SubstitutePointerType((PointerTypeSymbol)previous); break; case SymbolKind.FunctionPointerType: result = SubstituteFunctionPointerType((FunctionPointerTypeSymbol)previous); break; case SymbolKind.DynamicType: result = SubstituteDynamicType(); break; case SymbolKind.ErrorType: return ((ErrorTypeSymbol)previous).Substitute(this); default: result = previous; break; } return TypeWithAnnotations.Create(result); } internal TypeWithAnnotations SubstituteType(TypeWithAnnotations previous) { return previous.SubstituteType(this); } internal virtual ImmutableArray<CustomModifier> SubstituteCustomModifiers(ImmutableArray<CustomModifier> customModifiers) { if (customModifiers.IsDefaultOrEmpty) { return customModifiers; } for (int i = 0; i < customModifiers.Length; i++) { NamedTypeSymbol modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; var substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { var builder = ArrayBuilder<CustomModifier>.GetInstance(customModifiers.Length); builder.AddRange(customModifiers, i); builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); for (i++; i < customModifiers.Length; i++) { modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); } else { builder.Add(customModifiers[i]); } } Debug.Assert(builder.Count == customModifiers.Length); return builder.ToImmutableAndFree(); } } return customModifiers; } protected virtual TypeSymbol SubstituteDynamicType() { return DynamicTypeSymbol.Instance; } protected virtual TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) { return TypeWithAnnotations.Create(typeParameter); } private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t) { var oldElement = t.ElementTypeWithAnnotations; TypeWithAnnotations element = oldElement.SubstituteType(this); if (element.IsSameAs(oldElement)) { return t; } if (t.IsSZArray) { ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics(); Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2); if (interfaces.Length == 1) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0])); } else if (interfaces.Length == 2) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0]), SubstituteNamedType(interfaces[1])); } else if (interfaces.Length != 0) { throw ExceptionUtilities.Unreachable; } return ArrayTypeSymbol.CreateSZArray( element, t.BaseTypeNoUseSiteDiagnostics, interfaces); } return ArrayTypeSymbol.CreateMDArray( element, t.Rank, t.Sizes, t.LowerBounds, t.BaseTypeNoUseSiteDiagnostics); } private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t) { var oldPointedAtType = t.PointedAtTypeWithAnnotations; var pointedAtType = oldPointedAtType.SubstituteType(this); if (pointedAtType.IsSameAs(oldPointedAtType)) { return t; } return new PointerTypeSymbol(pointedAtType); } private FunctionPointerTypeSymbol SubstituteFunctionPointerType(FunctionPointerTypeSymbol f) { var substitutedReturnType = f.Signature.ReturnTypeWithAnnotations.SubstituteType(this); var refCustomModifiers = f.Signature.RefCustomModifiers; var substitutedRefCustomModifiers = SubstituteCustomModifiers(refCustomModifiers); var parameterTypesWithAnnotations = f.Signature.ParameterTypesWithAnnotations; ImmutableArray<TypeWithAnnotations> substitutedParamTypes = SubstituteTypes(parameterTypesWithAnnotations); ImmutableArray<ImmutableArray<CustomModifier>> substitutedParamModifiers = default; var paramCount = f.Signature.Parameters.Length; if (paramCount > 0) { var builder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool didSubstitute = false; foreach (var param in f.Signature.Parameters) { var substituted = SubstituteCustomModifiers(param.RefCustomModifiers); builder.Add(substituted); if (substituted != param.RefCustomModifiers) { didSubstitute = true; } } if (didSubstitute) { substitutedParamModifiers = builder.ToImmutableAndFree(); } else { builder.Free(); } } if (substitutedParamTypes != parameterTypesWithAnnotations || !substitutedParamModifiers.IsDefault || !f.Signature.ReturnTypeWithAnnotations.IsSameAs(substitutedReturnType) || substitutedRefCustomModifiers != refCustomModifiers) { f = f.SubstituteTypeSymbol(substitutedReturnType, substitutedParamTypes, refCustomModifiers, substitutedParamModifiers); } return f; } internal ImmutableArray<TypeSymbol> SubstituteTypesWithoutModifiers(ImmutableArray<TypeSymbol> original) { if (original.IsDefault) { return original; } TypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteType(t).Type; if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new TypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } internal ImmutableArray<TypeWithAnnotations> SubstituteTypes(ImmutableArray<TypeWithAnnotations> original) { if (original.IsDefault) { return default(ImmutableArray<TypeWithAnnotations>); } var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(original.Length); foreach (TypeWithAnnotations t in original) { result.Add(SubstituteType(t)); } return result.ToImmutableAndFree(); } /// <summary> /// Substitute types, and return the results without duplicates, preserving the original order. /// Note, all occurrences of 'dynamic' in resulting types will be replaced with 'object'. /// </summary> internal void SubstituteConstraintTypesDistinctWithoutModifiers( TypeParameterSymbol owner, ImmutableArray<TypeWithAnnotations> original, ArrayBuilder<TypeWithAnnotations> result, HashSet<TypeParameterSymbol> ignoreTypesDependentOnTypeParametersOpt) { DynamicTypeEraser dynamicEraser = null; if (original.Length == 0) { return; } else if (original.Length == 1) { var type = original[0]; if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { result.Add(substituteConstraintType(type)); } } else { var map = PooledDictionary<TypeSymbol, int>.GetInstance(); foreach (var type in original) { if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { var substituted = substituteConstraintType(type); if (!map.TryGetValue(substituted.Type, out int mergeWith)) { map.Add(substituted.Type, result.Count); result.Add(substituted); } else { result[mergeWith] = ConstraintsHelper.ConstraintWithMostSignificantNullability(result[mergeWith], substituted); } } } map.Free(); } TypeWithAnnotations substituteConstraintType(TypeWithAnnotations type) { if (dynamicEraser == null) { dynamicEraser = new DynamicTypeEraser(owner.ContainingAssembly.CorLibrary.GetSpecialType(SpecialType.System_Object)); } TypeWithAnnotations substituted = SubstituteType(type); return substituted.WithTypeAndModifiers(dynamicEraser.EraseDynamic(substituted.Type), substituted.CustomModifiers); } } internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original) { return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp).AsTypeSymbolOnly(), this); } /// <summary> /// Like SubstTypes, but for NamedTypeSymbols. /// </summary> internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original) { NamedTypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteNamedType(t); if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new NamedTypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/TypeDocumentationCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public TypeDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"enum Color { Red, Blue, Green } namespace Acme { interface IProcess {...} struct ValueType {...} class Widget: IProcess { /// <summary> /// Hello! Nested Class. /// </summary> public class NestedClass {...} public interface IMenuItem {...} public delegate void Del(int i); public enum Direction { North, South, East, West } } class MyList<T> { class Helper<U,V> {...} } }"); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestEnum() { Assert.Equal("T:Color", _compilation.GlobalNamespace.GetTypeMembers("Color").Single().GetDocumentationCommentId()); } [Fact] public void TestInterface() { Assert.Equal("T:Acme.IProcess", _acmeNamespace.GetTypeMembers("IProcess").Single().GetDocumentationCommentId()); } [Fact] public void TestStruct() { Assert.Equal("T:Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetDocumentationCommentId()); } [Fact] public void TestClass() { Assert.Equal("T:Acme.Widget", _widgetClass.GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { var classSymbol = _widgetClass.GetTypeMembers("NestedClass").Single(); Assert.Equal("T:Acme.Widget.NestedClass", classSymbol.GetDocumentationCommentId()); Assert.Equal( @"<member name=""T:Acme.Widget.NestedClass""> <summary> Hello! Nested Class. </summary> </member> ", classSymbol.GetDocumentationCommentXml()); } [Fact] public void TestNestedInterface() { Assert.Equal("T:Acme.Widget.IMenuItem", _widgetClass.GetMembers("IMenuItem").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedDelegate() { Assert.Equal("T:Acme.Widget.Del", _widgetClass.GetTypeMembers("Del").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedEnum() { Assert.Equal("T:Acme.Widget.Direction", _widgetClass.GetTypeMembers("Direction").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericType() { Assert.Equal("T:Acme.MyList`1", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetDocumentationCommentId()); } [Fact] public void TestNestedGenericType() { Assert.Equal("T:Acme.MyList`1.Helper`2", _acmeNamespace.GetTypeMembers("MyList", 1).Single() .GetTypeMembers("Helper", 2).Single().GetDocumentationCommentId()); } [Fact] public void TestDynamicType() { Assert.Null(DynamicTypeSymbol.Instance.GetDocumentationCommentId()); } [WorkItem(536957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536957")] [Fact] public void TestCommentsWithQuestionMarks() { var text = @" /// <doc><?pi ?></doc> /// <d><?pi some data ? > <??></d> /// <a></a><?pi data?> /// <do><?pi x /// y?></do> class A { } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public TypeDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"enum Color { Red, Blue, Green } namespace Acme { interface IProcess {...} struct ValueType {...} class Widget: IProcess { /// <summary> /// Hello! Nested Class. /// </summary> public class NestedClass {...} public interface IMenuItem {...} public delegate void Del(int i); public enum Direction { North, South, East, West } } class MyList<T> { class Helper<U,V> {...} } }"); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestEnum() { Assert.Equal("T:Color", _compilation.GlobalNamespace.GetTypeMembers("Color").Single().GetDocumentationCommentId()); } [Fact] public void TestInterface() { Assert.Equal("T:Acme.IProcess", _acmeNamespace.GetTypeMembers("IProcess").Single().GetDocumentationCommentId()); } [Fact] public void TestStruct() { Assert.Equal("T:Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetDocumentationCommentId()); } [Fact] public void TestClass() { Assert.Equal("T:Acme.Widget", _widgetClass.GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { var classSymbol = _widgetClass.GetTypeMembers("NestedClass").Single(); Assert.Equal("T:Acme.Widget.NestedClass", classSymbol.GetDocumentationCommentId()); Assert.Equal( @"<member name=""T:Acme.Widget.NestedClass""> <summary> Hello! Nested Class. </summary> </member> ", classSymbol.GetDocumentationCommentXml()); } [Fact] public void TestNestedInterface() { Assert.Equal("T:Acme.Widget.IMenuItem", _widgetClass.GetMembers("IMenuItem").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedDelegate() { Assert.Equal("T:Acme.Widget.Del", _widgetClass.GetTypeMembers("Del").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedEnum() { Assert.Equal("T:Acme.Widget.Direction", _widgetClass.GetTypeMembers("Direction").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericType() { Assert.Equal("T:Acme.MyList`1", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetDocumentationCommentId()); } [Fact] public void TestNestedGenericType() { Assert.Equal("T:Acme.MyList`1.Helper`2", _acmeNamespace.GetTypeMembers("MyList", 1).Single() .GetTypeMembers("Helper", 2).Single().GetDocumentationCommentId()); } [Fact] public void TestDynamicType() { Assert.Null(DynamicTypeSymbol.Instance.GetDocumentationCommentId()); } [WorkItem(536957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536957")] [Fact] public void TestCommentsWithQuestionMarks() { var text = @" /// <doc><?pi ?></doc> /// <d><?pi some data ? > <??></d> /// <a></a><?pi data?> /// <do><?pi x /// y?></do> class A { } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Analyzers/CSharp/CodeFixes/NewLines/EmbeddedStatementPlacement/EmbeddedStatementPlacementCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.NewLines.EmbeddedStatementPlacement { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.EmbeddedStatementPlacement), Shared] internal sealed class EmbeddedStatementPlacementCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EmbeddedStatementPlacementCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.EmbeddedStatementPlacementDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix( new MyCodeAction(c => UpdateDocumentAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } private static Task<Document> UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken); public static async Task<Document> FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif var endOfLineTrivia = SyntaxFactory.ElasticEndOfLine(options.GetOption(FormattingOptions2.NewLine, LanguageNames.CSharp)); foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, endOfLineTrivia, cancellationToken); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static void FixOne( SyntaxEditor editor, Diagnostic diagnostic, SyntaxTrivia endOfLineTrivia, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var root = editor.OriginalRoot; var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan); if (node is not StatementSyntax startStatement) { Debug.Fail("Couldn't find statement in fixer"); return; } // fixup this statement and all nested statements that have an issue. var descendentStatements = startStatement.DescendantNodesAndSelf().OfType<StatementSyntax>(); var badStatements = descendentStatements.Where(s => EmbeddedStatementPlacementDiagnosticAnalyzer.StatementNeedsWrapping(s)); // Walk from lower statements to higher so the higher up changes see the changes below. foreach (var badStatement in badStatements.OrderByDescending(s => s.SpanStart)) { editor.ReplaceNode( badStatement, (currentBadStatement, _) => { // Ensure a newline between the statement and the statement that preceded it. var updatedStatement = AddLeadingTrivia(currentBadStatement, endOfLineTrivia); // Ensure that if we wrap an empty block that the trailing brace is on a new line as well. if (updatedStatement is BlockSyntax blockSyntax && blockSyntax.Statements.Count == 0) { updatedStatement = blockSyntax.WithCloseBraceToken( AddLeadingTrivia(blockSyntax.CloseBraceToken, SyntaxFactory.ElasticMarker)); } return updatedStatement; }); } // Now walk up all our containing blocks ensuring that they wrap over multiple lines var ancestorBlocks = startStatement.AncestorsAndSelf().OfType<BlockSyntax>(); foreach (var block in ancestorBlocks) { var openBrace = block.OpenBraceToken; var previousToken = openBrace.GetPreviousToken(); editor.ReplaceNode( block, (current, _) => { // If the block's open { is not already on a new line, add an elastic marker so it will be placed there. var currentBlock = (BlockSyntax)current; if (!EmbeddedStatementPlacementDiagnosticAnalyzer.ContainsEndOfLineBetween(previousToken, openBrace)) { currentBlock = currentBlock.WithOpenBraceToken( AddLeadingTrivia(currentBlock.OpenBraceToken, SyntaxFactory.ElasticMarker)); } return currentBlock.WithCloseBraceToken( AddLeadingTrivia(currentBlock.CloseBraceToken, SyntaxFactory.ElasticMarker)); }); } } private static SyntaxNode AddLeadingTrivia(SyntaxNode node, SyntaxTrivia trivia) => node.WithLeadingTrivia(node.GetLeadingTrivia().Insert(0, trivia)); private static SyntaxToken AddLeadingTrivia(SyntaxToken token, SyntaxTrivia trivia) => token.WithLeadingTrivia(token.LeadingTrivia.Insert(0, trivia)); public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create( async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpCodeFixesResources.Place_statement_on_following_line, createChangedDocument, CSharpCodeFixesResources.Place_statement_on_following_line) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.NewLines.EmbeddedStatementPlacement { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.EmbeddedStatementPlacement), Shared] internal sealed class EmbeddedStatementPlacementCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EmbeddedStatementPlacementCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.EmbeddedStatementPlacementDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix( new MyCodeAction(c => UpdateDocumentAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } private static Task<Document> UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken); public static async Task<Document> FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(editor.OriginalRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif var endOfLineTrivia = SyntaxFactory.ElasticEndOfLine(options.GetOption(FormattingOptions2.NewLine, LanguageNames.CSharp)); foreach (var diagnostic in diagnostics) FixOne(editor, diagnostic, endOfLineTrivia, cancellationToken); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static void FixOne( SyntaxEditor editor, Diagnostic diagnostic, SyntaxTrivia endOfLineTrivia, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var root = editor.OriginalRoot; var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan); if (node is not StatementSyntax startStatement) { Debug.Fail("Couldn't find statement in fixer"); return; } // fixup this statement and all nested statements that have an issue. var descendentStatements = startStatement.DescendantNodesAndSelf().OfType<StatementSyntax>(); var badStatements = descendentStatements.Where(s => EmbeddedStatementPlacementDiagnosticAnalyzer.StatementNeedsWrapping(s)); // Walk from lower statements to higher so the higher up changes see the changes below. foreach (var badStatement in badStatements.OrderByDescending(s => s.SpanStart)) { editor.ReplaceNode( badStatement, (currentBadStatement, _) => { // Ensure a newline between the statement and the statement that preceded it. var updatedStatement = AddLeadingTrivia(currentBadStatement, endOfLineTrivia); // Ensure that if we wrap an empty block that the trailing brace is on a new line as well. if (updatedStatement is BlockSyntax blockSyntax && blockSyntax.Statements.Count == 0) { updatedStatement = blockSyntax.WithCloseBraceToken( AddLeadingTrivia(blockSyntax.CloseBraceToken, SyntaxFactory.ElasticMarker)); } return updatedStatement; }); } // Now walk up all our containing blocks ensuring that they wrap over multiple lines var ancestorBlocks = startStatement.AncestorsAndSelf().OfType<BlockSyntax>(); foreach (var block in ancestorBlocks) { var openBrace = block.OpenBraceToken; var previousToken = openBrace.GetPreviousToken(); editor.ReplaceNode( block, (current, _) => { // If the block's open { is not already on a new line, add an elastic marker so it will be placed there. var currentBlock = (BlockSyntax)current; if (!EmbeddedStatementPlacementDiagnosticAnalyzer.ContainsEndOfLineBetween(previousToken, openBrace)) { currentBlock = currentBlock.WithOpenBraceToken( AddLeadingTrivia(currentBlock.OpenBraceToken, SyntaxFactory.ElasticMarker)); } return currentBlock.WithCloseBraceToken( AddLeadingTrivia(currentBlock.CloseBraceToken, SyntaxFactory.ElasticMarker)); }); } } private static SyntaxNode AddLeadingTrivia(SyntaxNode node, SyntaxTrivia trivia) => node.WithLeadingTrivia(node.GetLeadingTrivia().Insert(0, trivia)); private static SyntaxToken AddLeadingTrivia(SyntaxToken token, SyntaxTrivia trivia) => token.WithLeadingTrivia(token.LeadingTrivia.Insert(0, trivia)); public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create( async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpCodeFixesResources.Place_statement_on_following_line, createChangedDocument, CSharpCodeFixesResources.Place_statement_on_following_line) { } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/Core/Portable/SolutionCrawler/HostSolutionCrawlerWorkspaceEventListener.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal class HostSolutionCrawlerWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HostSolutionCrawlerWorkspaceEventListener() { } public void StartListening(Workspace workspace, object? serviceOpt) { var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Register(workspace); } public void StopListening(Workspace workspace) { // we do this so that we can stop solution crawler faster and fire some telemetry. // this is to reduce a case where we keep going even when VS is shutting down since we don't know about that var registration = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); registration.Unregister(workspace, blockingShutdown: true); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/CommandLine/SarifErrorLoggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class SarifErrorLoggerTests : CommandLineTestBase { protected abstract string ErrorLogQualifier { get; } internal abstract string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd); internal abstract string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification); protected void NoDiagnosticsImpl() { var helloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; var hello = Temp.CreateFile().WriteAllText(helloWorldCS).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", hello, $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString().Trim()); Assert.Equal(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForNoDiagnostics(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(hello); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsImpl() { var source = @" public class C { private int x; }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsSuppressedImpl() { var source = @" public class C { #pragma warning disable CS0169 private int x; #pragma warning restore CS0169 }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsWithAndWithoutLocationImpl() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); string[] arguments = new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = ""Justification1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = ""Justification2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, "Justification1"); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = """")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = """")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, ""); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithNullJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = null)] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = null)] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public abstract class SarifErrorLoggerTests : CommandLineTestBase { protected abstract string ErrorLogQualifier { get; } internal abstract string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd); internal abstract string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd); internal abstract string GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(MockCSharpCompiler cmd, string justification); protected void NoDiagnosticsImpl() { var helloWorldCS = @"using System; class C { public static void Main(string[] args) { Console.WriteLine(""Hello, world""); } }"; var hello = Temp.CreateFile().WriteAllText(helloWorldCS).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", hello, $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString().Trim()); Assert.Equal(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForNoDiagnostics(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(hello); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsImpl() { var source = @" public class C { private int x; }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForSimpleCompilerDiagnostics(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void SimpleCompilerDiagnosticsSuppressedImpl() { var source = @" public class C { #pragma warning disable CS0169 private int x; #pragma warning restore CS0169 }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("CS0169", actualConsoleOutput); Assert.Contains("CS5001", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(cmd, sourceFile); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsWithAndWithoutLocationImpl() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); string[] arguments = new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(cmd); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = ""Justification1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = ""Justification2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, "Justification1"); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithMissingJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithEmptyJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = """")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = """")] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, ""); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } protected void AnalyzerDiagnosticsSuppressedWithNullJustificationImpl() { var source = @" [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category1"", ""ID1"", Justification = null)] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Category2"", ""ID2"", Justification = null)] class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var errorLogDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(errorLogDir.Path, "ErrorLog.txt"); string[] arguments = new[] { "/nologo", "/t:library", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}{ErrorLogQualifier}" }; var cmd = CreateCSharpCompiler(null, WorkingDirectory, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerForErrorLogTest())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); // Suppressed diagnostics are only reported in the error log, not the console output. Assert.DoesNotContain("Category1", actualConsoleOutput); Assert.DoesNotContain("Category2", actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); string expectedOutput = GetExpectedOutputForAnalyzerDiagnosticsWithSuppression(cmd, null); Assert.Equal(expectedOutput, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(errorLogFile); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/TestUtilities/Squiggles/SquiggleUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { public static class SquiggleUtilities { // Squiggle tests require solution crawler to run. internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures .RemoveParts(typeof(MockWorkspaceEventListenerProvider)); internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap); var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using var disposable = tagger as IDisposable; await wrapper.WaitForTags(); var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return (analyzerDiagnostics, spans); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles { public static class SquiggleUtilities { // Squiggle tests require solution crawler to run. internal static TestComposition CompositionWithSolutionCrawler = EditorTestCompositions.EditorFeatures .RemoveParts(typeof(MockWorkspaceEventListenerProvider)); internal static async Task<(ImmutableArray<DiagnosticData>, ImmutableArray<ITagSpan<IErrorTag>>)> GetDiagnosticsAndErrorSpansAsync<TProvider>( TestWorkspace workspace, IReadOnlyDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzerMap = null) where TProvider : AbstractDiagnosticsAdornmentTaggerProvider<IErrorTag> { using var wrapper = new DiagnosticTaggerWrapper<TProvider, IErrorTag>(workspace, analyzerMap); var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer()); using var disposable = tagger as IDisposable; await wrapper.WaitForTags(); var analyzerDiagnostics = await wrapper.AnalyzerService.GetDiagnosticsAsync(workspace.CurrentSolution); var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot; var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToImmutableArray(); return (analyzerDiagnostics, spans); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/CodeAnalysisTest/Collections/SimpleElementImmutablesTestBase.cs
// Licensed to the .NET Foundation under one or more 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/runtime: // https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/SimpleElementImmutablesTestBase.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract class SimpleElementImmutablesTestBase : ImmutablesTestBase { protected abstract IEnumerable<T> GetEnumerableOf<T>(params T[] contents); protected IEnumerable<T> GetEnumerableOf<T>(IEnumerable<T> contents) { return GetEnumerableOf(contents.ToArray()); } } }
// Licensed to the .NET Foundation under one or more 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/runtime: // https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/SimpleElementImmutablesTestBase.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract class SimpleElementImmutablesTestBase : ImmutablesTestBase { protected abstract IEnumerable<T> GetEnumerableOf<T>(params T[] contents); protected IEnumerable<T> GetEnumerableOf<T>(IEnumerable<T> contents) { return GetEnumerableOf(contents.ToArray()); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/CSharp/Test/CallHierarchy/CSharpCallHierarchyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy { [UseExportProvider] public class CSharpCallHierarchyTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnProperty() { var text = @" namespace N { class C { public int G$$oo { get; set;} } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnEvent() { var text = @" using System; namespace N { class C { public event EventHandler Go$$o; } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_FindCalls() { var text = @" namespace N { class C { void G$$oo() { } } class G { void Main() { var c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_InterfaceImplementation() { var text = @" namespace N { interface I { void Goo(); } class C : I { public void G$$oo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToOverride() { var text = @" namespace N { class C { protected virtual void G$$oo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" }); testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" }); } [WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToBase() { var text = @" namespace N { class C { protected virtual void Goo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Go$$o(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldInitializers() { var text = @" namespace N { class C { public int goo = Goo(); protected int Goo$$() { return 0; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldReferences() { var text = @" namespace N { class C { public int g$$oo = Goo(); protected int Goo() { goo = 3; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void PropertyGet() { var text = @" namespace N { class C { public int val { g$$et { return 0; } } public int goo() { var x = this.val; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Generic() { var text = @" namespace N { class C { public int gen$$eric<T>(this string generic, ref T stuff) { return 0; } public int goo() { int i; generic("", ref i); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void ExtensionMethods() { var text = @" namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var x = ""string""; x.BarStr$$ing(); } } public static class Extensions { public static string BarString(this string s) { return s; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void GenericExtensionMethods() { var text = @" using System.Collections.Generic; using System.Linq; namespace N { class Program { static void Main(string[] args) { List<int> x = new List<int>(); var z = x.Si$$ngle(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InterfaceImplementors() { var text = @" namespace N { interface I { void Go$$o(); } class C : I { public async Task Goo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void NoFindOverridesOnSealedMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FindOverrides() { var text = @" namespace N { class C { public virtual void G$$oo() { } } class G : C { public override void Goo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" }); } [WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")] [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void AbstractMethodInclusionToOverrides() { var text = @" using System; abstract class Base { public abstract void $$M(); } class Derived : Base { public override void M() { throw new NotImplementedException(); } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void SearchAfterEditWorks() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */"); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CallHierarchy { [UseExportProvider] public class CSharpCallHierarchyTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnProperty() { var text = @" namespace N { class C { public int G$$oo { get; set;} } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InvokeOnEvent() { var text = @" using System; namespace N { class C { public event EventHandler Go$$o; } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_FindCalls() { var text = @" namespace N { class C { void G$$oo() { } } class G { void Main() { var c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()", "N.G.Main2()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_InterfaceImplementation() { var text = @" namespace N { interface I { void Goo(); } class C : I { public void G$$oo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main2()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, "N.I.Goo()"), new[] { "N.G.Main()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToOverride() { var text = @" namespace N { class C { protected virtual void G$$oo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Bar()" }); testState.VerifyResult(root, EditorFeaturesResources.Calls_To_Overrides, new[] { "N.D.Baz()" }); } [WpfFact, WorkItem(829705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829705"), Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Method_CallToBase() { var text = @" namespace N { class C { protected virtual void Goo() { } } class D : C { protected override void Goo() { } void Bar() { C c; c.Goo() } void Baz() { D d; d.Go$$o(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.D.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.D.Baz()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, "N.C.Goo()"), new[] { "N.D.Bar()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldInitializers() { var text = @" namespace N { class C { public int goo = Goo(); protected int Goo$$() { return 0; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo") }); testState.VerifyResultName(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { EditorFeaturesResources.Initializers }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FieldReferences() { var text = @" namespace N { class C { public int g$$oo = Goo(); protected int Goo() { goo = 3; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.goo", new[] { string.Format(EditorFeaturesResources.References_To_Field_0, "goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.References_To_Field_0, "goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void PropertyGet() { var text = @" namespace N { class C { public int val { g$$et { return 0; } } public int goo() { var x = this.val; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.val.get", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "get_val") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "get_val"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void Generic() { var text = @" namespace N { class C { public int gen$$eric<T>(this string generic, ref T stuff) { return 0; } public int goo() { int i; generic("", ref i); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.generic<T>(this string, ref T)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "generic") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "generic"), new[] { "N.C.goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void ExtensionMethods() { var text = @" namespace ConsoleApplication10 { class Program { static void Main(string[] args) { var x = ""string""; x.BarStr$$ing(); } } public static class Extensions { public static string BarString(this string s) { return s; } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "ConsoleApplication10.Extensions.BarString(this string)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "BarString") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "BarString"), new[] { "ConsoleApplication10.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void GenericExtensionMethods() { var text = @" using System.Collections.Generic; using System.Linq; namespace N { class Program { static void Main(string[] args) { List<int> x = new List<int>(); var z = x.Si$$ngle(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "System.Linq.Enumerable.Single<TSource>(this System.Collections.Generic.IEnumerable<TSource>)", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Single") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Single"), new[] { "N.Program.Main(string[])" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void InterfaceImplementors() { var text = @" namespace N { interface I { void Go$$o(); } class C : I { public async Task Goo() { } } class G { void Main() { I c = new C(); c.Goo(); } void Main2() { var c = new C(); c.Goo(); } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.I.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), string.Format(EditorFeaturesResources.Implements_0, "Goo") }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), new[] { "N.G.Main()" }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Implements_0, "Goo"), new[] { "N.C.Goo()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void NoFindOverridesOnSealedMethod() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); Assert.DoesNotContain("Overrides", root.SupportedSearchCategories.Select(s => s.DisplayName)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void FindOverrides() { var text = @" namespace N { class C { public virtual void G$$oo() { } } class G : C { public override void Goo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), EditorFeaturesResources.Overrides_ }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "N.G.Goo()" }); } [WorkItem(844613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844613")] [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void AbstractMethodInclusionToOverrides() { var text = @" using System; abstract class Base { public abstract void $$M(); } class Derived : Base { public override void M() { throw new NotImplementedException(); } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.VerifyRoot(root, "Base.M()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "M"), EditorFeaturesResources.Overrides_, EditorFeaturesResources.Calls_To_Overrides }); testState.VerifyResult(root, EditorFeaturesResources.Overrides_, new[] { "Derived.M()" }); } [WpfFact, Trait(Traits.Feature, Traits.Features.CallHierarchy)] public void SearchAfterEditWorks() { var text = @" namespace N { class C { void G$$oo() { } } }"; using var testState = CallHierarchyTestState.Create(text); var root = testState.GetRoot(); testState.Workspace.Documents.Single().GetTextBuffer().Insert(0, "/* hello */"); testState.VerifyRoot(root, "N.C.Goo()", new[] { string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), }); testState.VerifyResult(root, string.Format(EditorFeaturesResources.Calls_To_0, "Goo"), expectedCallers: new[] { "N.C.Goo()" }); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/AssemblyReaders.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct AssemblyReaders { public readonly MetadataReader MetadataReader; public readonly object SymReader; public AssemblyReaders(MetadataReader metadataReader, object symReader) { MetadataReader = metadataReader; SymReader = symReader; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Reflection.Metadata; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct AssemblyReaders { public readonly MetadataReader MetadataReader; public readonly object SymReader; public AssemblyReaders(MetadataReader metadataReader, object symReader) { MetadataReader = metadataReader; SymReader = symReader; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolVisibility.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Utilities { internal enum SymbolVisibility { Public, Internal, Private, } }
// Licensed to the .NET Foundation under one or more 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.Shared.Utilities { internal enum SymbolVisibility { Public, Internal, Private, } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReadOnlyListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Utilities { internal static class IReadOnlyListExtensions { public static IReadOnlyList<T> ToReadOnlyList<T>(this IList<T> list) { if (list is IReadOnlyList<T> readOnlyList) { return readOnlyList; } return new ReadOnlyList<T>(list); } public static T Last<T>(this IReadOnlyList<T> list) => list[list.Count - 1]; public static int IndexOf<T>(this IReadOnlyList<T> list, T value, int startIndex = 0) { for (var index = startIndex; index < list.Count; index++) { if (EqualityComparer<T>.Default.Equals(list[index], value)) { return index; } } return -1; } private class ReadOnlyList<T> : IReadOnlyList<T> { private readonly IList<T> _list; public ReadOnlyList(IList<T> list) => _list = list; public T this[int index] => _list[index]; public int Count => _list.Count; public IEnumerator<T> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Utilities { internal static class IReadOnlyListExtensions { public static IReadOnlyList<T> ToReadOnlyList<T>(this IList<T> list) { if (list is IReadOnlyList<T> readOnlyList) { return readOnlyList; } return new ReadOnlyList<T>(list); } public static T Last<T>(this IReadOnlyList<T> list) => list[list.Count - 1]; public static int IndexOf<T>(this IReadOnlyList<T> list, T value, int startIndex = 0) { for (var index = startIndex; index < list.Count; index++) { if (EqualityComparer<T>.Default.Equals(list[index], value)) { return index; } } return -1; } private class ReadOnlyList<T> : IReadOnlyList<T> { private readonly IList<T> _list; public ReadOnlyList(IList<T> list) => _list = list; public T this[int index] => _list[index]; public int Count => _list.Count; public IEnumerator<T> GetEnumerator() => _list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/CodeAnalysisTest/Diagnostics/AnalysisContextInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class AnalysisContextInfoTests { [Fact] public void InitializeTest() { var code = @"class C { void M() { return; } }"; var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None) .WithFeatures(new[] { new KeyValuePair<string, string>("IOperation", "true") }); var compilation = CreateCompilation(code, parseOptions: parseOptions); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSemanticModelAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSymbolAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxNodeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxTreeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterAdditionalFileAction)); } private static void Verify(Compilation compilation, AnalyzerOptions options, string context) { var analyzer = new Analyzer(s => context == s); var diagnostics = compilation.GetAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, options); Assert.Equal(1, diagnostics.Length); Assert.True(diagnostics[0].Descriptor.Description.ToString().IndexOf(analyzer.Info.GetContext()) >= 0); } private class Analyzer : DiagnosticAnalyzer { public const string Id = "exception"; private static readonly DiagnosticDescriptor s_rule = GetRule(Id); private readonly Func<string, bool> _throwPredicate; private AnalysisContextInfo _info; public Analyzer(Func<string, bool> throwPredicate) { _throwPredicate = throwPredicate; } public AnalysisContextInfo Info => _info; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); public override void Initialize(AnalysisContext c) { c.RegisterCodeBlockAction(b => ThrowIfMatch(nameof(c.RegisterCodeBlockAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCodeBlockStartAction<SyntaxKind>(b => ThrowIfMatch(nameof(c.RegisterCodeBlockStartAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCompilationAction(b => ThrowIfMatch(nameof(c.RegisterCompilationAction), new AnalysisContextInfo(b.Compilation))); c.RegisterCompilationStartAction(b => ThrowIfMatch(nameof(c.RegisterCompilationStartAction), new AnalysisContextInfo(b.Compilation))); c.RegisterOperationAction(b => ThrowIfMatch(nameof(c.RegisterOperationAction), new AnalysisContextInfo(b.Compilation, b.Operation)), OperationKind.Return); c.RegisterOperationBlockAction(b => ThrowIfMatch(nameof(c.RegisterOperationBlockAction), new AnalysisContextInfo(b.Compilation, b.OwningSymbol))); c.RegisterSemanticModelAction(b => ThrowIfMatch(nameof(c.RegisterSemanticModelAction), new AnalysisContextInfo(b.SemanticModel))); c.RegisterSymbolAction(b => ThrowIfMatch(nameof(c.RegisterSymbolAction), new AnalysisContextInfo(b.Compilation, b.Symbol)), SymbolKind.NamedType); c.RegisterSyntaxNodeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxNodeAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.Node)), SyntaxKind.ReturnStatement); c.RegisterSyntaxTreeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxTreeAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.Tree)))); c.RegisterAdditionalFileAction(b => ThrowIfMatch(nameof(c.RegisterAdditionalFileAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.AdditionalFile)))); } private void ThrowIfMatch(string context, AnalysisContextInfo info) { if (!_throwPredicate(context)) { return; } _info = info; throw new Exception("exception"); } } private static DiagnosticDescriptor GetRule(string id) { return new DiagnosticDescriptor( id, id, "{0}", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); } private static Compilation CreateCompilation(string source, CSharpParseOptions parseOptions = null) { string fileName = "Test.cs"; string projectName = "TestProject"; var syntaxTree = CSharpSyntaxTree.ParseText(source, path: fileName, options: parseOptions); return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: new[] { TestBase.MscorlibRef }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class AnalysisContextInfoTests { [Fact] public void InitializeTest() { var code = @"class C { void M() { return; } }"; var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.None) .WithFeatures(new[] { new KeyValuePair<string, string>("IOperation", "true") }); var compilation = CreateCompilation(code, parseOptions: parseOptions); var options = new AnalyzerOptions(new[] { new TestAdditionalText() }.ToImmutableArray<AdditionalText>()); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCodeBlockStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterCompilationStartAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterOperationBlockAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSemanticModelAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSymbolAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxNodeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterSyntaxTreeAction)); Verify(compilation, options, nameof(AnalysisContext.RegisterAdditionalFileAction)); } private static void Verify(Compilation compilation, AnalyzerOptions options, string context) { var analyzer = new Analyzer(s => context == s); var diagnostics = compilation.GetAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, options); Assert.Equal(1, diagnostics.Length); Assert.True(diagnostics[0].Descriptor.Description.ToString().IndexOf(analyzer.Info.GetContext()) >= 0); } private class Analyzer : DiagnosticAnalyzer { public const string Id = "exception"; private static readonly DiagnosticDescriptor s_rule = GetRule(Id); private readonly Func<string, bool> _throwPredicate; private AnalysisContextInfo _info; public Analyzer(Func<string, bool> throwPredicate) { _throwPredicate = throwPredicate; } public AnalysisContextInfo Info => _info; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); public override void Initialize(AnalysisContext c) { c.RegisterCodeBlockAction(b => ThrowIfMatch(nameof(c.RegisterCodeBlockAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCodeBlockStartAction<SyntaxKind>(b => ThrowIfMatch(nameof(c.RegisterCodeBlockStartAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.OwningSymbol, b.CodeBlock))); c.RegisterCompilationAction(b => ThrowIfMatch(nameof(c.RegisterCompilationAction), new AnalysisContextInfo(b.Compilation))); c.RegisterCompilationStartAction(b => ThrowIfMatch(nameof(c.RegisterCompilationStartAction), new AnalysisContextInfo(b.Compilation))); c.RegisterOperationAction(b => ThrowIfMatch(nameof(c.RegisterOperationAction), new AnalysisContextInfo(b.Compilation, b.Operation)), OperationKind.Return); c.RegisterOperationBlockAction(b => ThrowIfMatch(nameof(c.RegisterOperationBlockAction), new AnalysisContextInfo(b.Compilation, b.OwningSymbol))); c.RegisterSemanticModelAction(b => ThrowIfMatch(nameof(c.RegisterSemanticModelAction), new AnalysisContextInfo(b.SemanticModel))); c.RegisterSymbolAction(b => ThrowIfMatch(nameof(c.RegisterSymbolAction), new AnalysisContextInfo(b.Compilation, b.Symbol)), SymbolKind.NamedType); c.RegisterSyntaxNodeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxNodeAction), new AnalysisContextInfo(b.SemanticModel.Compilation, b.Node)), SyntaxKind.ReturnStatement); c.RegisterSyntaxTreeAction(b => ThrowIfMatch(nameof(c.RegisterSyntaxTreeAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.Tree)))); c.RegisterAdditionalFileAction(b => ThrowIfMatch(nameof(c.RegisterAdditionalFileAction), new AnalysisContextInfo(b.Compilation, new SourceOrAdditionalFile(b.AdditionalFile)))); } private void ThrowIfMatch(string context, AnalysisContextInfo info) { if (!_throwPredicate(context)) { return; } _info = info; throw new Exception("exception"); } } private static DiagnosticDescriptor GetRule(string id) { return new DiagnosticDescriptor( id, id, "{0}", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); } private static Compilation CreateCompilation(string source, CSharpParseOptions parseOptions = null) { string fileName = "Test.cs"; string projectName = "TestProject"; var syntaxTree = CSharpSyntaxTree.ParseText(source, path: fileName, options: parseOptions); return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: new[] { TestBase.MscorlibRef }); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/VisualBasicTest/Recommendations/EventHandling/RaiseEventKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.EventHandling Public Class RaiseEventKeywordRecommenderTests Inherits RecommenderTests <Fact> <WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub RaiseEventInCustomEventTest() Dim code = <File> Public Class Z Public Custom Event E As Action | End Event End Class</File> VerifyRecommendationsContain(code, "RaiseEvent") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub RaiseEventInSingleLineLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "RaiseEvent") End Sub <Fact> <WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotRaiseEventInCustomEventWithRaiseEventTest() Dim code = <File> Public Class Z Public Custom Event E As Action RaiseEvent() End RaiseEvent | End Event End Class</File> VerifyRecommendationsMissing(code, "RaiseEvent") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.EventHandling Public Class RaiseEventKeywordRecommenderTests Inherits RecommenderTests <Fact> <WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub RaiseEventInCustomEventTest() Dim code = <File> Public Class Z Public Custom Event E As Action | End Event End Class</File> VerifyRecommendationsContain(code, "RaiseEvent") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub RaiseEventInSingleLineLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "RaiseEvent") End Sub <Fact> <WorkItem(808406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/808406")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotRaiseEventInCustomEventWithRaiseEventTest() Dim code = <File> Public Class Z Public Custom Event E As Action RaiseEvent() End RaiseEvent | End Event End Class</File> VerifyRecommendationsMissing(code, "RaiseEvent") End Sub End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_IsUnmanaged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_IsUnmanaged : CSharpTestBase { [Fact] public void AttributeUsedIfExists_FromSource_Method() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Class() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_LocalFunction() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M() { void N<T>(T arg) where T : unmanaged { } } } "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Delegate() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public delegate void D<T>() where T : unmanaged; "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Method() { var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Class() { var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_LocalFunction() { var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Delegate() { var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Delegates() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public delegate void D([IsUnmanaged]int x); "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2), // (10,25): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public delegate void D([IsUnmanaged]int x); Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(10, 25)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Types() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Fields() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int x = 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Properties() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int Property => 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Methods() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] [return: IsUnmanaged] public int Method([IsUnmanaged]int x) { return x; } } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [return: IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 14), // (13,24): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int Method([IsUnmanaged]int x) Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(13, 24)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Indexers() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int this[[IsUnmanaged]int x] => x; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,22): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int this[[IsUnmanaged]int x] => x; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 22)); } [Fact] public void UserReferencingIsUnmanagedAttributeShouldResultInAnError() { var code = @" [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'IsUnmanagedAttribute' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanagedAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'IsUnmanaged' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanaged").WithLocation(2, 2)); } [Fact] public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }"); var code2 = CreateCompilation(@" public class Test1<T> where T : unmanaged { } ", references: new[] { code1.ToMetadataReference() }, options: options); CompileAndVerify(code2, symbolValidator: module => { AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); var code3 = CreateCompilation(@" public class Test2<T> : Test1<T> where T : unmanaged { } ", references: new[] { code2.ToMetadataReference() }, options: options); CompileAndVerify(code3, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Type() { var code = @" public class Test<T> where T : unmanaged { }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (2,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(2, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public void M<T>() where T : unmanaged {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(4, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } N<int>(); } }"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // void N<T>() where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(6, 16)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (1,24): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public delegate void D<T>() where T : unmanaged; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(1, 24)); } [Fact] public void ReferencingAnEmbeddedIsUnmanagedAttributeDoesNotUseIt_InternalsVisible() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = @" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")] public class Test1<T> where T : unmanaged { }"; var comp1 = CompileAndVerify(code1, options: options, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test1`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); var code2 = @" public class Test2<T> : Test1<T> where T : unmanaged { }"; CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithWrongConstructorSignature(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { public IsUnmanagedAttribute(int p) { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithPrivateConstructor(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { private IsUnmanagedAttribute() { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsAsInterface(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public interface IsUnmanagedAttribute { } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (6,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(6, 12)); } internal static void AssertReferencedIsUnmanagedAttribute(Accessibility accessibility, TypeParameterSymbol typeParameter, string assemblyName) { var attributes = ((PEModuleSymbol)typeParameter.ContainingModule).GetCustomAttributesForToken(((PETypeParameterSymbol)typeParameter).Handle); NamedTypeSymbol attributeType = attributes.Single().AttributeClass; Assert.Equal("IsUnmanagedAttribute", attributeType.Name); Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name); Assert.Equal(accessibility, attributeType.DeclaredAccessibility); switch (accessibility) { case Accessibility.Internal: { var isUnmanagedTypeAttributes = attributeType.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray(); Assert.Equal(2, isUnmanagedTypeAttributes.Length); Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), isUnmanagedTypeAttributes[0].AttributeClass.ToDisplayString()); Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, isUnmanagedTypeAttributes[1].AttributeClass.ToDisplayString()); break; } case Accessibility.Public: { Assert.Null(attributeType.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); break; } default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } private void AssertNoIsUnmanagedAttributeExists(AssemblySymbol assembly) { var isUnmanagedAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute); Assert.Null(assembly.GetTypeByMetadataName(isUnmanagedAttributeTypeName)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_IsUnmanaged : CSharpTestBase { [Fact] public void AttributeUsedIfExists_FromSource_Method() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Class() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_LocalFunction() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { public void M() { void N<T>(T arg) where T : unmanaged { } } } "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromSource_Delegate() { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public delegate void D<T>() where T : unmanaged; "; CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Reference() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), references: new[] { reference }, symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Method_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Class_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_LocalFunction_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } } "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeUsedIfExists_FromReference_Delegate_Module() { var reference = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }").EmitToImageReference(); var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Public, typeParameter, reference.Display); AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Method() { var text = @" public class Test { public void M<T>() where T : unmanaged { } } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Class() { var text = @" public class Test<T> where T : unmanaged { } "; CompileAndVerify(text, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_LocalFunction() { var text = @" public class Test { public void M() { void N<T>() where T : unmanaged { } { } } } "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void AttributeGeneratedIfNotExists_FromSource_Delegate() { var text = @" public delegate void D<T>() where T : unmanaged; "; CompileAndVerify( source: text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Delegates() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public delegate void D([IsUnmanaged]int x); "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2), // (10,25): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public delegate void D([IsUnmanaged]int x); Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(10, 25)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Types() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (9,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(9, 2)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Fields() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int x = 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Properties() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int Property => 0; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Methods() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] [return: IsUnmanaged] public int Method([IsUnmanaged]int x) { return x; } } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [return: IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 14), // (13,24): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int Method([IsUnmanaged]int x) Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(13, 24)); } [Fact] public void IsUnmanagedAttributeIsDisallowedEverywhereInSource_Indexers() { var code = @" using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } } public class Test { [IsUnmanaged] public int this[[IsUnmanaged]int x] => x; } "; CreateCompilation(code).VerifyDiagnostics( // (11,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // [IsUnmanaged] Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(11, 6), // (12,22): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage. // public int this[[IsUnmanaged]int x] => x; Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(12, 22)); } [Fact] public void UserReferencingIsUnmanagedAttributeShouldResultInAnError() { var code = @" [IsUnmanaged] public class Test { } "; CreateCompilation(code).VerifyDiagnostics( // (2,2): error CS0246: The type or namespace name 'IsUnmanagedAttribute' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanagedAttribute").WithLocation(2, 2), // (2,2): error CS0246: The type or namespace name 'IsUnmanaged' could not be found (are you missing a using directive or an assembly reference?) // [IsUnmanaged] Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsUnmanaged").WithArguments("IsUnmanaged").WithLocation(2, 2)); } [Fact] public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = CreateCompilation(@" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { } }"); var code2 = CreateCompilation(@" public class Test1<T> where T : unmanaged { } ", references: new[] { code1.ToMetadataReference() }, options: options); CompileAndVerify(code2, symbolValidator: module => { AssertNoIsUnmanagedAttributeExists(module.ContainingAssembly); }); var code3 = CreateCompilation(@" public class Test2<T> : Test1<T> where T : unmanaged { } ", references: new[] { code2.ToMetadataReference() }, options: options); CompileAndVerify(code3, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Type() { var code = @" public class Test<T> where T : unmanaged { }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (2,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(2, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics( // (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public void M<T>() where T : unmanaged {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(4, 19)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } N<int>(); } }"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (6,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // void N<T>() where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(6, 16)); } [Fact] public void BuildingAModuleRequiresIsUnmanagedAttributeToBeThere_Missing_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; CreateCompilation(source: code, options: TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All)).VerifyDiagnostics( // (1,24): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsUnmanagedAttribute' is not defined or imported // public delegate void D<T>() where T : unmanaged; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(1, 24)); } [Fact] public void ReferencingAnEmbeddedIsUnmanagedAttributeDoesNotUseIt_InternalsVisible() { var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); var code1 = @" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")] public class Test1<T> where T : unmanaged { }"; var comp1 = CompileAndVerify(code1, options: options, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test1`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); var code2 = @" public class Test2<T> : Test1<T> where T : unmanaged { }"; CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test2`1").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertReferencedIsUnmanagedAttribute(Accessibility.Internal, typeParameter, module.ContainingAssembly.Name); }); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithWrongConstructorSignature(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { public IsUnmanagedAttribute(int p) { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsWithPrivateConstructor(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public class IsUnmanagedAttribute : System.Attribute { private IsUnmanagedAttribute() { } } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (9,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(9, 12)); } [Theory] [InlineData(OutputKind.DynamicallyLinkedLibrary)] [InlineData(OutputKind.NetModule)] public void IsUnmanagedAttributeExistsAsInterface(OutputKind outputKind) { var text = @" namespace System.Runtime.CompilerServices { public interface IsUnmanagedAttribute { } } class Test<T> where T : unmanaged { }"; CreateCompilation(text, options: TestOptions.DebugDll.WithOutputKind(outputKind)).VerifyDiagnostics( // (6,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsUnmanagedAttribute..ctor' // class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute", ".ctor").WithLocation(6, 12)); } internal static void AssertReferencedIsUnmanagedAttribute(Accessibility accessibility, TypeParameterSymbol typeParameter, string assemblyName) { var attributes = ((PEModuleSymbol)typeParameter.ContainingModule).GetCustomAttributesForToken(((PETypeParameterSymbol)typeParameter).Handle); NamedTypeSymbol attributeType = attributes.Single().AttributeClass; Assert.Equal("IsUnmanagedAttribute", attributeType.Name); Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name); Assert.Equal(accessibility, attributeType.DeclaredAccessibility); switch (accessibility) { case Accessibility.Internal: { var isUnmanagedTypeAttributes = attributeType.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray(); Assert.Equal(2, isUnmanagedTypeAttributes.Length); Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), isUnmanagedTypeAttributes[0].AttributeClass.ToDisplayString()); Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, isUnmanagedTypeAttributes[1].AttributeClass.ToDisplayString()); break; } case Accessibility.Public: { Assert.Null(attributeType.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName)); break; } default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } private void AssertNoIsUnmanagedAttributeExists(AssemblySymbol assembly) { var isUnmanagedAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute); Assert.Null(assembly.GetTypeByMetadataName(isUnmanagedAttributeTypeName)); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.FunctionType) { return CreateFunctionTypeConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { return new BoundConversion( syntax, BindUnconvertedInterpolatedExpressionToHandlerType(source, (NamedTypeSymbol)destination, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateFunctionTypeConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.Kind == ConversionKind.FunctionType); Debug.Assert(source.Kind is BoundKind.MethodGroup or BoundKind.UnboundLambda); Debug.Assert(syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = source.GetInferredDelegateType(ref useSiteInfo); Debug.Assert(delegateType is { }); if (source.Kind == BoundKind.UnboundLambda && destination.IsNonGenericExpressionType()) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } conversion = Conversions.ClassifyConversionFromExpression(source, delegateType, ref useSiteInfo); bool warnOnMethodGroupConversion = source.Kind == BoundKind.MethodGroup && !isCast && conversion.Exists && destination.SpecialType == SpecialType.System_Object; BoundExpression expr; if (!conversion.Exists) { GenerateImplicitConversionError(diagnostics, syntax, conversion, source, delegateType); expr = new BoundConversion(syntax, source, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: delegateType, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } else { expr = CreateConversion(syntax, source, conversion, isCast, conversionGroup, delegateType, diagnostics); } conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); if (!conversion.Exists) { GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); } else if (warnOnMethodGroupConversion) { Error(diagnostics, ErrorCode.WRN_MethGrpToNonDel, syntax, ((BoundMethodGroup)source).Name, destination); } diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, group.FunctionType, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Debug.Assert(Conversions.IsAssignableFromMulticastDelegate(delegateOrFuncPtrType, ref discardedUseSiteInfo) || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (!Conversions.IsAssignableFromMulticastDelegate(delegateOrFuncPtrType, ref discardedUseSiteInfo)) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.FunctionType) { return CreateFunctionTypeConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { return new BoundConversion( syntax, BindUnconvertedInterpolatedExpressionToHandlerType(source, (NamedTypeSymbol)destination, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateFunctionTypeConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.Kind == ConversionKind.FunctionType); Debug.Assert(source.Kind is BoundKind.MethodGroup or BoundKind.UnboundLambda); Debug.Assert(syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = source.GetInferredDelegateType(ref useSiteInfo); Debug.Assert(delegateType is { }); if (source.Kind == BoundKind.UnboundLambda && destination.IsNonGenericExpressionType()) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } conversion = Conversions.ClassifyConversionFromExpression(source, delegateType, ref useSiteInfo); bool warnOnMethodGroupConversion = source.Kind == BoundKind.MethodGroup && !isCast && conversion.Exists && destination.SpecialType == SpecialType.System_Object; BoundExpression expr; if (!conversion.Exists) { GenerateImplicitConversionError(diagnostics, syntax, conversion, source, delegateType); expr = new BoundConversion(syntax, source, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: delegateType, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } else { expr = CreateConversion(syntax, source, conversion, isCast, conversionGroup, delegateType, diagnostics); } conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); if (!conversion.Exists) { GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); } else if (warnOnMethodGroupConversion) { Error(diagnostics, ErrorCode.WRN_MethGrpToNonDel, syntax, ((BoundMethodGroup)source).Name, destination); } diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, group.FunctionType, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Debug.Assert(Conversions.IsAssignableFromMulticastDelegate(delegateOrFuncPtrType, ref discardedUseSiteInfo) || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (!Conversions.IsAssignableFromMulticastDelegate(delegateOrFuncPtrType, ref discardedUseSiteInfo)) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/Portable/DocumentationComments/DocumentationCommentIncludeCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class DocumentationCommentIncludeCache : CachingFactory<string, KeyValuePair<string, XDocument>> { // TODO: tune private const int Size = 5; /// <summary> /// WARN: This is a test hook - do not take a dependency on this. /// </summary> internal static int CacheMissCount { get; private set; } public DocumentationCommentIncludeCache(XmlReferenceResolver resolver) : base(Size, key => MakeValue(resolver, key), KeyHashCode, KeyValueEquality) { CacheMissCount = 0; } public XDocument GetOrMakeDocument(string resolvedPath) { return GetOrMakeValue(resolvedPath).Value; } private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings() { // Dev12 prohibits DTD DtdProcessing = DtdProcessing.Prohibit }; /// <exception cref="IOException"></exception> /// <exception cref="XmlException"></exception> /// <exception cref="InvalidOperationException"></exception> private static KeyValuePair<string, XDocument> MakeValue(XmlReferenceResolver resolver, string resolvedPath) { CacheMissCount++; using (Stream stream = resolver.OpenReadChecked(resolvedPath)) { using (XmlReader reader = XmlReader.Create(stream, s_xmlSettings)) { var document = XDocument.Load(reader, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo); return KeyValuePairUtil.Create(resolvedPath, document); } } } private static int KeyHashCode(string resolvedPath) { return resolvedPath.GetHashCode(); } private static bool KeyValueEquality(string resolvedPath, KeyValuePair<string, XDocument> pathAndDocument) { return resolvedPath == pathAndDocument.Key; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class DocumentationCommentIncludeCache : CachingFactory<string, KeyValuePair<string, XDocument>> { // TODO: tune private const int Size = 5; /// <summary> /// WARN: This is a test hook - do not take a dependency on this. /// </summary> internal static int CacheMissCount { get; private set; } public DocumentationCommentIncludeCache(XmlReferenceResolver resolver) : base(Size, key => MakeValue(resolver, key), KeyHashCode, KeyValueEquality) { CacheMissCount = 0; } public XDocument GetOrMakeDocument(string resolvedPath) { return GetOrMakeValue(resolvedPath).Value; } private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings() { // Dev12 prohibits DTD DtdProcessing = DtdProcessing.Prohibit }; /// <exception cref="IOException"></exception> /// <exception cref="XmlException"></exception> /// <exception cref="InvalidOperationException"></exception> private static KeyValuePair<string, XDocument> MakeValue(XmlReferenceResolver resolver, string resolvedPath) { CacheMissCount++; using (Stream stream = resolver.OpenReadChecked(resolvedPath)) { using (XmlReader reader = XmlReader.Create(stream, s_xmlSettings)) { var document = XDocument.Load(reader, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo); return KeyValuePairUtil.Create(resolvedPath, document); } } } private static int KeyHashCode(string resolvedPath) { return resolvedPath.GetHashCode(); } private static bool KeyValueEquality(string resolvedPath, KeyValuePair<string, XDocument> pathAndDocument) { return resolvedPath == pathAndDocument.Key; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/BoundTree/BoundDagEvaluation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { partial class BoundDagEvaluation { public override bool Equals([NotNullWhen(true)] object? obj) => obj is BoundDagEvaluation other && this.Equals(other); public virtual bool Equals(BoundDagEvaluation other) { return this == other || this.Kind == other.Kind && this.Input.Equals(other.Input) && this.Symbol.Equals(other.Symbol, TypeCompareKind.AllIgnoreOptions); } private Symbol Symbol { get { switch (this) { case BoundDagFieldEvaluation e: return e.Field.CorrespondingTupleField ?? e.Field; case BoundDagPropertyEvaluation e: return e.Property; case BoundDagTypeEvaluation e: return e.Type; case BoundDagDeconstructEvaluation e: return e.DeconstructMethod; case BoundDagIndexEvaluation e: return e.Property; default: throw ExceptionUtilities.UnexpectedValue(this.Kind); } } } public override int GetHashCode() { return Hash.Combine(Input.GetHashCode(), this.Symbol?.GetHashCode() ?? 0); } #if DEBUG private int _id = -1; public int Id { get { return _id; } internal set { Debug.Assert(value > 0, "Id must be positive but was set to " + value); Debug.Assert(_id == -1, $"Id was set to {_id} and set again to {value}"); _id = value; } } internal string GetOutputTempDebuggerDisplay() { var id = Id; return id switch { -1 => "<uninitialized>", // Note that we never expect to create an evaluation with id 0 // To do so would imply that dag evaluation assigns to the original input 0 => "<error>", _ => $"t{id}" }; } #endif } partial class BoundDagIndexEvaluation { public override int GetHashCode() => base.GetHashCode() ^ this.Index; public override bool Equals(BoundDagEvaluation obj) { return this == obj || base.Equals(obj) && // base.Equals checks the kind field, so the following cast is safe this.Index == ((BoundDagIndexEvaluation)obj).Index; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { partial class BoundDagEvaluation { public override bool Equals([NotNullWhen(true)] object? obj) => obj is BoundDagEvaluation other && this.Equals(other); public virtual bool Equals(BoundDagEvaluation other) { return this == other || this.Kind == other.Kind && this.Input.Equals(other.Input) && this.Symbol.Equals(other.Symbol, TypeCompareKind.AllIgnoreOptions); } private Symbol Symbol { get { switch (this) { case BoundDagFieldEvaluation e: return e.Field.CorrespondingTupleField ?? e.Field; case BoundDagPropertyEvaluation e: return e.Property; case BoundDagTypeEvaluation e: return e.Type; case BoundDagDeconstructEvaluation e: return e.DeconstructMethod; case BoundDagIndexEvaluation e: return e.Property; default: throw ExceptionUtilities.UnexpectedValue(this.Kind); } } } public override int GetHashCode() { return Hash.Combine(Input.GetHashCode(), this.Symbol?.GetHashCode() ?? 0); } #if DEBUG private int _id = -1; public int Id { get { return _id; } internal set { Debug.Assert(value > 0, "Id must be positive but was set to " + value); Debug.Assert(_id == -1, $"Id was set to {_id} and set again to {value}"); _id = value; } } internal string GetOutputTempDebuggerDisplay() { var id = Id; return id switch { -1 => "<uninitialized>", // Note that we never expect to create an evaluation with id 0 // To do so would imply that dag evaluation assigns to the original input 0 => "<error>", _ => $"t{id}" }; } #endif } partial class BoundDagIndexEvaluation { public override int GetHashCode() => base.GetHashCode() ^ this.Index; public override bool Equals(BoundDagEvaluation obj) { return this == obj || base.Equals(obj) && // base.Equals checks the kind field, so the following cast is safe this.Index == ((BoundDagIndexEvaluation)obj).Index; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Portable/BoundTree/BoundExpressionExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Module BoundExpressionExtensions ' returns true when expression has no side-effects and produces ' default value (null, zero, false, default(T) ...) ' NOTE: This method is a very shallow check. ' It does not make any assumptions about what this node could become ' after some folding/propagation/algebraic transformations. <Extension> Public Function IsDefaultValue(node As BoundExpression) As Boolean Dim constValue As ConstantValue = node.ConstantValueOpt If constValue IsNot Nothing AndAlso constValue.IsDefaultValue Then Return True End If 'TODO: I have seen other places where we do similar digging. ' It seems a bit bug-prone. What if Nothing is wrapped in more than one conversion or a parenthesized or whatever...? ' Perhaps it may be worth it to introduce BoundDefault and reduce the "default value" patterns to ' a node with unambiguous meaning? ' there is no BoundDefault node in VB, 'default" is represented through several means ' so we need to match several patterns. Select Case node.Kind Case BoundKind.Conversion constValue = DirectCast(node, BoundConversion).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing Case BoundKind.DirectCast ' DirectCast(Nothing, <ValueType>) is emitted as an unbox on a null reference. ' It is not equivalent to a default value If node.Type.IsTypeParameter() OrElse Not node.Type.IsValueType Then constValue = DirectCast(node, BoundDirectCast).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing End If Case BoundKind.TryCast constValue = DirectCast(node, BoundTryCast).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing Case BoundKind.ObjectCreationExpression Dim ctor = DirectCast(node, BoundObjectCreationExpression).ConstructorOpt Return ctor Is Nothing OrElse ctor.IsDefaultValueTypeConstructor() End Select Return False End Function ' Is this a kind of bound node that can act as a value? This include variables, but does not ' include things like types or namespaces. <Extension()> Public Function IsValue(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Parenthesized Return DirectCast(node, BoundParenthesized).Expression.IsValue Case BoundKind.BadExpression Return node.Type IsNot Nothing Case BoundKind.TypeExpression, BoundKind.NamespaceExpression, BoundKind.MethodGroup, BoundKind.PropertyGroup, BoundKind.ArrayInitialization, BoundKind.TypeArguments, BoundKind.Label, BoundKind.EventAccess Return False Case Else Return True End Select End Function <Extension()> Public Function IsMeReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MeReference End Function <Extension()> Public Function IsMyBaseReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MyBaseReference End Function <Extension()> Public Function IsMyClassReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MyClassReference End Function ''' <summary> Returns True if the node specified is one of Me/MyClass/MyBase </summary> <Extension()> Public Function IsInstanceReference(node As BoundExpression) As Boolean Return node.IsMeReference OrElse node.IsMyBaseReference OrElse node.IsMyClassReference End Function ''' <summary> ''' Returns True if the expression is a property access expression, ''' either directly or wrapped in an XML member access expression. ''' </summary> <Extension()> Public Function IsPropertyOrXmlPropertyAccess(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.IsPropertyOrXmlPropertyAccess() Case BoundKind.PropertyAccess Return True Case Else Return False End Select End Function <Extension()> Public Function IsPropertyReturnsByRef(node As BoundExpression) As Boolean Return node.Kind = BoundKind.PropertyAccess AndAlso DirectCast(node, BoundPropertyAccess).PropertySymbol.ReturnsByRef End Function <Extension()> Public Function IsLateBound(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.LateMemberAccess, BoundKind.LateInvocation Return True Case Else Return False End Select End Function <Extension()> Public Function GetTypeOfAssignmentTarget(node As BoundExpression) As TypeSymbol Debug.Assert(node.IsSupportingAssignment()) If node.Kind = BoundKind.PropertyAccess Then Return DirectCast(node, BoundPropertyAccess).PropertySymbol.GetTypeFromSetMethod() End If Return node.Type End Function <Extension()> Public Function GetPropertyOrXmlProperty(node As BoundExpression) As PropertySymbol Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.GetPropertyOrXmlProperty() Case BoundKind.PropertyAccess Return DirectCast(node, BoundPropertyAccess).PropertySymbol Case Else Return Nothing End Select End Function ''' <summary> ''' Does this node represent a property with Set accessor and AccessKind not yet bound to Get? ''' </summary> <Extension()> Public Function IsPropertySupportingAssignment(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.IsPropertySupportingAssignment() Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) If propertyAccess.AccessKind = PropertyAccessKind.Get Then Return False End If Return propertyAccess.IsWriteable Case Else Return False End Select End Function ''' <summary> ''' Does this node represent a property or latebound access not yet determined to be Get? ''' </summary> <Extension()> Public Function IsSupportingAssignment(node As BoundExpression) As Boolean If node Is Nothing Then Return False End If If node.IsLValue Then Return True End If Select Case node.Kind Case BoundKind.LateMemberAccess Dim member = DirectCast(node, BoundLateMemberAccess) Return member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call Case BoundKind.LateInvocation Dim invocation = DirectCast(node, BoundLateInvocation) If invocation.AccessKind = LateBoundAccessKind.Unknown Then Dim group = invocation.MethodOrPropertyGroupOpt If group IsNot Nothing AndAlso group.Kind = BoundKind.MethodGroup Then ' latebound invocation of a method group is considered not assignable ' NOTE: interestingly, property group is considered assignable even if all properties are readonly. Return False End If End If Return invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call Case BoundKind.LateBoundArgumentSupportingAssignmentWithCapture Return True Case Else Return IsPropertySupportingAssignment(node) End Select End Function ''' <summary> ''' Get the access kind from property access expression. ''' </summary> <Extension()> Public Function GetAccessKind(node As BoundExpression) As PropertyAccessKind Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.GetAccessKind() Case BoundKind.PropertyAccess Return DirectCast(node, BoundPropertyAccess).AccessKind Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function GetLateBoundAccessKind(node As BoundExpression) As LateBoundAccessKind Select Case node.Kind Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).AccessKind Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).AccessKind Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ''' <summary> ''' Sets the access kind on the property access expression. To clear the access ''' kind, 'newAccessKind' should be Unknown. Otherwise, the current property ''' access kind should be Unknown or equal to 'newAccessKind'. ''' </summary> <Extension()> Public Function SetAccessKind(node As BoundExpression, newAccessKind As PropertyAccessKind) As BoundExpression Select Case node.Kind Case BoundKind.XmlMemberAccess Dim memberAccess = DirectCast(node, BoundXmlMemberAccess) Return memberAccess.SetAccessKind(newAccessKind) Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) Debug.Assert(Not propertyAccess.PropertySymbol.ReturnsByRef OrElse (newAccessKind And PropertyAccessKind.Set) = 0) Return propertyAccess.SetAccessKind(newAccessKind) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function SetLateBoundAccessKind(node As BoundExpression, newAccessKind As LateBoundAccessKind) As BoundExpression Select Case node.Kind Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).SetAccessKind(newAccessKind) Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).SetAccessKind(newAccessKind) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function SetAccessKind(node As BoundXmlMemberAccess, newAccessKind As PropertyAccessKind) As BoundXmlMemberAccess Dim expr = node.MemberAccess.SetAccessKind(newAccessKind) Return node.Update(expr) End Function <Extension()> Public Function SetGetSetAccessKindIfAppropriate(node As BoundExpression) As BoundExpression Select Case node.Kind Case BoundKind.XmlMemberAccess Dim memberAccess = DirectCast(node, BoundXmlMemberAccess) Return memberAccess.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) Dim accessKind = If(propertyAccess.PropertySymbol.ReturnsByRef, PropertyAccessKind.Get, PropertyAccessKind.Get Or PropertyAccessKind.Set) Return propertyAccess.SetAccessKind(accessKind) Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).SetAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Case Else Return node End Select End Function ''' <summary> ''' Return a BoundXmlMemberAccess node with ''' updated MemberAccess property. ''' </summary> <Extension()> Public Function Update(node As BoundXmlMemberAccess, memberAccess As BoundExpression) As BoundXmlMemberAccess Return node.Update(memberAccess, memberAccess.Type) End Function ''' <summary> ''' Return true if and only if an expression is a integral literal with a value of zero. ''' Non-literal constant value zero does not qualify. ''' </summary> <Extension()> Public Function IsIntegerZeroLiteral(node As BoundExpression) As Boolean ' Dev10 treats parenthesized 0 as a literal. While node.Kind = BoundKind.Parenthesized node = DirectCast(node, BoundParenthesized).Expression End While Return node.Kind = BoundKind.Literal AndAlso IsIntegerZeroLiteral(DirectCast(node, BoundLiteral)) End Function ''' <summary> ''' Return true if and only if an expression is a integral literal with a value of zero. ''' Non-literal constant value zero does not qualify. ''' </summary> <Extension()> Public Function IsIntegerZeroLiteral(node As BoundLiteral) As Boolean Debug.Assert(node.Value.IsBad OrElse node.Type.IsValidForConstantValue(node.Value)) If node.Value.Discriminator = ConstantValueTypeDiscriminator.Int32 AndAlso node.Type.SpecialType = SpecialType.System_Int32 Then Return node.Value.Int32Value = 0 End If Return False End Function ''' <summary> ''' Checks if the expression is a default value (0 or Nothing) ''' </summary> <Extension()> Public Function IsDefaultValueConstant(expr As BoundExpression) As Boolean Dim c = expr.ConstantValueOpt Return c IsNot Nothing AndAlso c.IsDefaultValue End Function ''' <summary> ''' Checks if the expression is a constant and that constant is False ''' </summary> <Extension()> Public Function IsTrueConstant(expr As BoundExpression) As Boolean Return expr.ConstantValueOpt Is ConstantValue.True End Function ''' <summary> ''' Checks if the expression is a constant and that constant is True ''' </summary> <Extension()> Public Function IsFalseConstant(expr As BoundExpression) As Boolean Return expr.ConstantValueOpt Is ConstantValue.False End Function ''' <summary> ''' Checks if the expression is a negative integer constant value. ''' </summary> <Extension()> Public Function IsNegativeIntegerConstant(expression As BoundExpression) As Boolean Debug.Assert(expression IsNot Nothing) If expression.GetIntegerConstantValue() < 0 Then Return True End If Return False End Function ''' <summary> ''' Return the integer constant value (if any) from a BoundExpression ''' </summary> <Extension()> Public Function GetIntegerConstantValue(expression As BoundExpression) As Integer? Debug.Assert(expression IsNot Nothing) If Not expression.HasErrors AndAlso expression.IsConstant Then Dim type As SpecialType = expression.Type.SpecialType Select Case type Case SpecialType.System_Int16 Return expression.ConstantValueOpt.Int16Value Case SpecialType.System_Int32 Return expression.ConstantValueOpt.Int32Value Case SpecialType.System_Int64 If expression.ConstantValueOpt.Int64Value <= Integer.MaxValue AndAlso expression.ConstantValueOpt.Int64Value >= Integer.MinValue Then Return CInt(expression.ConstantValueOpt.Int64Value) End If Return Nothing End Select End If Return Nothing End Function ''' <summary> ''' Return true if and only if an expression is a semantical Nothing literal, ''' which is defined as follows (the definition is consistent with ''' definition used by Dev10 compiler): ''' - A Nothing literal according to the language grammar, or ''' - A parenthesized expression, for which IsNothingLiteral returns true, or ''' - An expression of type Object with constant value == Nothing. ''' </summary> <Extension()> Public Function IsNothingLiteral(node As BoundExpression) As Boolean Dim type = node.Type If type Is Nothing OrElse type.SpecialType = SpecialType.System_Object Then Dim constantValue = node.ConstantValueOpt If constantValue IsNot Nothing AndAlso constantValue.IsNothing Then Debug.Assert(type IsNot Nothing OrElse node.Kind = BoundKind.Literal OrElse node.Kind = BoundKind.Parenthesized) Return True End If End If Return False End Function ''' <summary> ''' Return true if target BoundLiteral represents Nothing literal as defined by the language grammar. ''' </summary> <Extension()> Public Function IsNothingLiteral(node As BoundLiteral) As Boolean If node.Value.IsNothing Then Debug.Assert(node.Type Is Nothing) Return node.Type Is Nothing End If Return False End Function ''' <summary> ''' Return true if and only if an expression represents optionally ''' parenthesized Nothing literal as defined by the language grammar. ''' I.e. implicit conversions are Ok, but explicit conversions aren't. ''' </summary> <Extension()> Public Function IsStrictNothingLiteral(node As BoundExpression) As Boolean If Not IsNothingLiteral(node) Then Return False End If Dim constantValue As ConstantValue ' Dev10 treats parenthesized NOTHING as a literal. Do Select Case node.Kind Case BoundKind.Literal Return IsNothingLiteral(DirectCast(node, BoundLiteral)) Case BoundKind.Parenthesized Dim parenthesized = DirectCast(node, BoundParenthesized) node = parenthesized.Expression Case BoundKind.Conversion Dim conversion = DirectCast(node, BoundConversion) constantValue = conversion.ConstantValueOpt If Not (Not conversion.ExplicitCastInCode AndAlso constantValue IsNot Nothing AndAlso constantValue.IsNothing) Then Return False End If node = conversion.Operand Case Else Return False End Select Loop End Function <Extension()> Public Function GetMostEnclosedParenthesizedExpression(expression As BoundExpression) As BoundExpression While expression.Kind = BoundKind.Parenthesized expression = DirectCast(expression, BoundParenthesized).Expression End While Return expression End Function <Extension()> Public Function HasExpressionSymbols(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Call, BoundKind.Local, BoundKind.RangeVariable, BoundKind.FieldAccess, BoundKind.PropertyAccess, BoundKind.EventAccess, BoundKind.MethodGroup, BoundKind.PropertyGroup, BoundKind.ObjectCreationExpression, BoundKind.TypeExpression, BoundKind.NamespaceExpression, BoundKind.Conversion Return True Case BoundKind.BadExpression Return DirectCast(node, BoundBadExpression).Symbols.Length > 0 Case Else Return False End Select End Function <Extension()> Public Sub GetExpressionSymbols(methodGroup As BoundMethodGroup, symbols As ArrayBuilder(Of Symbol)) Dim targetArity As Integer = 0 If methodGroup.TypeArgumentsOpt IsNot Nothing Then targetArity = methodGroup.TypeArgumentsOpt.Arguments.Length End If For Each method In methodGroup.Methods ' This is a quick fix for the fact that binder lookup in VB does not perform arity check for ' method symbols leaving it to overload resolution code. Here we filter wrong arity methods If targetArity = 0 Then symbols.Add(method) ElseIf targetArity = method.Arity Then symbols.Add(method.Construct(methodGroup.TypeArgumentsOpt.Arguments)) End If Next ' Merge methodGroup.AdditionalExtensionMethods into the result. For Each method In methodGroup.AdditionalExtensionMethods(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) ' This is a quick fix for the fact that binder lookup in VB does not perform arity check for ' method symbols leaving it to overload resolution code. Here we filter wrong arity methods If targetArity = 0 Then symbols.Add(method) ElseIf targetArity = method.Arity Then symbols.Add(method.Construct(methodGroup.TypeArgumentsOpt.Arguments)) End If Next End Sub <Extension()> Public Sub GetExpressionSymbols(node As BoundExpression, symbols As ArrayBuilder(Of Symbol)) Select Case node.Kind Case BoundKind.MethodGroup DirectCast(node, BoundMethodGroup).GetExpressionSymbols(symbols) Case BoundKind.PropertyGroup symbols.AddRange(DirectCast(node, BoundPropertyGroup).Properties) Case BoundKind.BadExpression symbols.AddRange(DirectCast(node, BoundBadExpression).Symbols) Case BoundKind.QueryClause DirectCast(node, BoundQueryClause).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.AggregateClause DirectCast(node, BoundAggregateClause).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.Ordering DirectCast(node, BoundOrdering).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.QuerySource DirectCast(node, BoundQuerySource).Expression.GetExpressionSymbols(symbols) Case BoundKind.ToQueryableCollectionConversion DirectCast(node, BoundToQueryableCollectionConversion).ConversionCall.GetExpressionSymbols(symbols) Case BoundKind.QueryableSource DirectCast(node, BoundQueryableSource).Source.GetExpressionSymbols(symbols) Case Else Dim symbol = node.ExpressionSymbol If symbol IsNot Nothing Then If symbol.Kind = SymbolKind.Namespace AndAlso DirectCast(symbol, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then symbols.AddRange(DirectCast(symbol, NamespaceSymbol).ConstituentNamespaces) Else symbols.Add(symbol) End If End If End Select End Sub <Extension()> Public Function ToStatement(node As BoundExpression) As BoundExpressionStatement Return New BoundExpressionStatement(node.Syntax, node, node.HasErrors) End Function <Extension()> <Conditional("DEBUG")> Public Sub AssertRValue(node As BoundExpression) If Not node.HasErrors Then Debug.Assert(node.IsValue) Debug.Assert(Not node.IsLValue) Debug.Assert(Not node.IsPropertyOrXmlPropertyAccess() OrElse node.GetAccessKind() = PropertyAccessKind.Get) Debug.Assert(Not node.IsLateBound() OrElse node.GetLateBoundAccessKind() = LateBoundAccessKind.Get) Debug.Assert(If(node.Type Is Nothing, node.IsNothingLiteral() OrElse node.GetMostEnclosedParenthesizedExpression().Kind = BoundKind.AddressOfOperator OrElse node.GetMostEnclosedParenthesizedExpression().Kind = BoundKind.Lambda OrElse node.Kind = BoundKind.QueryLambda, Not node.Type.IsVoidType())) End If End Sub ''' <summary> ''' returns type arguments or Nothing if group does not have type arguments. ''' </summary> <Extension()> Friend Function TypeArguments(this As BoundMethodOrPropertyGroup) As BoundTypeArguments Dim asMethodGroup = TryCast(this, BoundMethodGroup) If asMethodGroup IsNot Nothing Then Return asMethodGroup.TypeArgumentsOpt End If Return Nothing End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Linq Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Module BoundExpressionExtensions ' returns true when expression has no side-effects and produces ' default value (null, zero, false, default(T) ...) ' NOTE: This method is a very shallow check. ' It does not make any assumptions about what this node could become ' after some folding/propagation/algebraic transformations. <Extension> Public Function IsDefaultValue(node As BoundExpression) As Boolean Dim constValue As ConstantValue = node.ConstantValueOpt If constValue IsNot Nothing AndAlso constValue.IsDefaultValue Then Return True End If 'TODO: I have seen other places where we do similar digging. ' It seems a bit bug-prone. What if Nothing is wrapped in more than one conversion or a parenthesized or whatever...? ' Perhaps it may be worth it to introduce BoundDefault and reduce the "default value" patterns to ' a node with unambiguous meaning? ' there is no BoundDefault node in VB, 'default" is represented through several means ' so we need to match several patterns. Select Case node.Kind Case BoundKind.Conversion constValue = DirectCast(node, BoundConversion).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing Case BoundKind.DirectCast ' DirectCast(Nothing, <ValueType>) is emitted as an unbox on a null reference. ' It is not equivalent to a default value If node.Type.IsTypeParameter() OrElse Not node.Type.IsValueType Then constValue = DirectCast(node, BoundDirectCast).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing End If Case BoundKind.TryCast constValue = DirectCast(node, BoundTryCast).Operand.ConstantValueOpt Return constValue IsNot Nothing AndAlso constValue.IsNothing Case BoundKind.ObjectCreationExpression Dim ctor = DirectCast(node, BoundObjectCreationExpression).ConstructorOpt Return ctor Is Nothing OrElse ctor.IsDefaultValueTypeConstructor() End Select Return False End Function ' Is this a kind of bound node that can act as a value? This include variables, but does not ' include things like types or namespaces. <Extension()> Public Function IsValue(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Parenthesized Return DirectCast(node, BoundParenthesized).Expression.IsValue Case BoundKind.BadExpression Return node.Type IsNot Nothing Case BoundKind.TypeExpression, BoundKind.NamespaceExpression, BoundKind.MethodGroup, BoundKind.PropertyGroup, BoundKind.ArrayInitialization, BoundKind.TypeArguments, BoundKind.Label, BoundKind.EventAccess Return False Case Else Return True End Select End Function <Extension()> Public Function IsMeReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MeReference End Function <Extension()> Public Function IsMyBaseReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MyBaseReference End Function <Extension()> Public Function IsMyClassReference(node As BoundExpression) As Boolean Return node.Kind = BoundKind.MyClassReference End Function ''' <summary> Returns True if the node specified is one of Me/MyClass/MyBase </summary> <Extension()> Public Function IsInstanceReference(node As BoundExpression) As Boolean Return node.IsMeReference OrElse node.IsMyBaseReference OrElse node.IsMyClassReference End Function ''' <summary> ''' Returns True if the expression is a property access expression, ''' either directly or wrapped in an XML member access expression. ''' </summary> <Extension()> Public Function IsPropertyOrXmlPropertyAccess(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.IsPropertyOrXmlPropertyAccess() Case BoundKind.PropertyAccess Return True Case Else Return False End Select End Function <Extension()> Public Function IsPropertyReturnsByRef(node As BoundExpression) As Boolean Return node.Kind = BoundKind.PropertyAccess AndAlso DirectCast(node, BoundPropertyAccess).PropertySymbol.ReturnsByRef End Function <Extension()> Public Function IsLateBound(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.LateMemberAccess, BoundKind.LateInvocation Return True Case Else Return False End Select End Function <Extension()> Public Function GetTypeOfAssignmentTarget(node As BoundExpression) As TypeSymbol Debug.Assert(node.IsSupportingAssignment()) If node.Kind = BoundKind.PropertyAccess Then Return DirectCast(node, BoundPropertyAccess).PropertySymbol.GetTypeFromSetMethod() End If Return node.Type End Function <Extension()> Public Function GetPropertyOrXmlProperty(node As BoundExpression) As PropertySymbol Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.GetPropertyOrXmlProperty() Case BoundKind.PropertyAccess Return DirectCast(node, BoundPropertyAccess).PropertySymbol Case Else Return Nothing End Select End Function ''' <summary> ''' Does this node represent a property with Set accessor and AccessKind not yet bound to Get? ''' </summary> <Extension()> Public Function IsPropertySupportingAssignment(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.IsPropertySupportingAssignment() Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) If propertyAccess.AccessKind = PropertyAccessKind.Get Then Return False End If Return propertyAccess.IsWriteable Case Else Return False End Select End Function ''' <summary> ''' Does this node represent a property or latebound access not yet determined to be Get? ''' </summary> <Extension()> Public Function IsSupportingAssignment(node As BoundExpression) As Boolean If node Is Nothing Then Return False End If If node.IsLValue Then Return True End If Select Case node.Kind Case BoundKind.LateMemberAccess Dim member = DirectCast(node, BoundLateMemberAccess) Return member.AccessKind <> LateBoundAccessKind.Get AndAlso member.AccessKind <> LateBoundAccessKind.Call Case BoundKind.LateInvocation Dim invocation = DirectCast(node, BoundLateInvocation) If invocation.AccessKind = LateBoundAccessKind.Unknown Then Dim group = invocation.MethodOrPropertyGroupOpt If group IsNot Nothing AndAlso group.Kind = BoundKind.MethodGroup Then ' latebound invocation of a method group is considered not assignable ' NOTE: interestingly, property group is considered assignable even if all properties are readonly. Return False End If End If Return invocation.AccessKind <> LateBoundAccessKind.Get AndAlso invocation.AccessKind <> LateBoundAccessKind.Call Case BoundKind.LateBoundArgumentSupportingAssignmentWithCapture Return True Case Else Return IsPropertySupportingAssignment(node) End Select End Function ''' <summary> ''' Get the access kind from property access expression. ''' </summary> <Extension()> Public Function GetAccessKind(node As BoundExpression) As PropertyAccessKind Select Case node.Kind Case BoundKind.XmlMemberAccess Return DirectCast(node, BoundXmlMemberAccess).MemberAccess.GetAccessKind() Case BoundKind.PropertyAccess Return DirectCast(node, BoundPropertyAccess).AccessKind Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function GetLateBoundAccessKind(node As BoundExpression) As LateBoundAccessKind Select Case node.Kind Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).AccessKind Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).AccessKind Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ''' <summary> ''' Sets the access kind on the property access expression. To clear the access ''' kind, 'newAccessKind' should be Unknown. Otherwise, the current property ''' access kind should be Unknown or equal to 'newAccessKind'. ''' </summary> <Extension()> Public Function SetAccessKind(node As BoundExpression, newAccessKind As PropertyAccessKind) As BoundExpression Select Case node.Kind Case BoundKind.XmlMemberAccess Dim memberAccess = DirectCast(node, BoundXmlMemberAccess) Return memberAccess.SetAccessKind(newAccessKind) Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) Debug.Assert(Not propertyAccess.PropertySymbol.ReturnsByRef OrElse (newAccessKind And PropertyAccessKind.Set) = 0) Return propertyAccess.SetAccessKind(newAccessKind) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function SetLateBoundAccessKind(node As BoundExpression, newAccessKind As LateBoundAccessKind) As BoundExpression Select Case node.Kind Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).SetAccessKind(newAccessKind) Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).SetAccessKind(newAccessKind) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function <Extension()> Public Function SetAccessKind(node As BoundXmlMemberAccess, newAccessKind As PropertyAccessKind) As BoundXmlMemberAccess Dim expr = node.MemberAccess.SetAccessKind(newAccessKind) Return node.Update(expr) End Function <Extension()> Public Function SetGetSetAccessKindIfAppropriate(node As BoundExpression) As BoundExpression Select Case node.Kind Case BoundKind.XmlMemberAccess Dim memberAccess = DirectCast(node, BoundXmlMemberAccess) Return memberAccess.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) Case BoundKind.PropertyAccess Dim propertyAccess = DirectCast(node, BoundPropertyAccess) Dim accessKind = If(propertyAccess.PropertySymbol.ReturnsByRef, PropertyAccessKind.Get, PropertyAccessKind.Get Or PropertyAccessKind.Set) Return propertyAccess.SetAccessKind(accessKind) Case BoundKind.LateMemberAccess Return DirectCast(node, BoundLateMemberAccess).SetAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Case BoundKind.LateInvocation Return DirectCast(node, BoundLateInvocation).SetAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Case Else Return node End Select End Function ''' <summary> ''' Return a BoundXmlMemberAccess node with ''' updated MemberAccess property. ''' </summary> <Extension()> Public Function Update(node As BoundXmlMemberAccess, memberAccess As BoundExpression) As BoundXmlMemberAccess Return node.Update(memberAccess, memberAccess.Type) End Function ''' <summary> ''' Return true if and only if an expression is a integral literal with a value of zero. ''' Non-literal constant value zero does not qualify. ''' </summary> <Extension()> Public Function IsIntegerZeroLiteral(node As BoundExpression) As Boolean ' Dev10 treats parenthesized 0 as a literal. While node.Kind = BoundKind.Parenthesized node = DirectCast(node, BoundParenthesized).Expression End While Return node.Kind = BoundKind.Literal AndAlso IsIntegerZeroLiteral(DirectCast(node, BoundLiteral)) End Function ''' <summary> ''' Return true if and only if an expression is a integral literal with a value of zero. ''' Non-literal constant value zero does not qualify. ''' </summary> <Extension()> Public Function IsIntegerZeroLiteral(node As BoundLiteral) As Boolean Debug.Assert(node.Value.IsBad OrElse node.Type.IsValidForConstantValue(node.Value)) If node.Value.Discriminator = ConstantValueTypeDiscriminator.Int32 AndAlso node.Type.SpecialType = SpecialType.System_Int32 Then Return node.Value.Int32Value = 0 End If Return False End Function ''' <summary> ''' Checks if the expression is a default value (0 or Nothing) ''' </summary> <Extension()> Public Function IsDefaultValueConstant(expr As BoundExpression) As Boolean Dim c = expr.ConstantValueOpt Return c IsNot Nothing AndAlso c.IsDefaultValue End Function ''' <summary> ''' Checks if the expression is a constant and that constant is False ''' </summary> <Extension()> Public Function IsTrueConstant(expr As BoundExpression) As Boolean Return expr.ConstantValueOpt Is ConstantValue.True End Function ''' <summary> ''' Checks if the expression is a constant and that constant is True ''' </summary> <Extension()> Public Function IsFalseConstant(expr As BoundExpression) As Boolean Return expr.ConstantValueOpt Is ConstantValue.False End Function ''' <summary> ''' Checks if the expression is a negative integer constant value. ''' </summary> <Extension()> Public Function IsNegativeIntegerConstant(expression As BoundExpression) As Boolean Debug.Assert(expression IsNot Nothing) If expression.GetIntegerConstantValue() < 0 Then Return True End If Return False End Function ''' <summary> ''' Return the integer constant value (if any) from a BoundExpression ''' </summary> <Extension()> Public Function GetIntegerConstantValue(expression As BoundExpression) As Integer? Debug.Assert(expression IsNot Nothing) If Not expression.HasErrors AndAlso expression.IsConstant Then Dim type As SpecialType = expression.Type.SpecialType Select Case type Case SpecialType.System_Int16 Return expression.ConstantValueOpt.Int16Value Case SpecialType.System_Int32 Return expression.ConstantValueOpt.Int32Value Case SpecialType.System_Int64 If expression.ConstantValueOpt.Int64Value <= Integer.MaxValue AndAlso expression.ConstantValueOpt.Int64Value >= Integer.MinValue Then Return CInt(expression.ConstantValueOpt.Int64Value) End If Return Nothing End Select End If Return Nothing End Function ''' <summary> ''' Return true if and only if an expression is a semantical Nothing literal, ''' which is defined as follows (the definition is consistent with ''' definition used by Dev10 compiler): ''' - A Nothing literal according to the language grammar, or ''' - A parenthesized expression, for which IsNothingLiteral returns true, or ''' - An expression of type Object with constant value == Nothing. ''' </summary> <Extension()> Public Function IsNothingLiteral(node As BoundExpression) As Boolean Dim type = node.Type If type Is Nothing OrElse type.SpecialType = SpecialType.System_Object Then Dim constantValue = node.ConstantValueOpt If constantValue IsNot Nothing AndAlso constantValue.IsNothing Then Debug.Assert(type IsNot Nothing OrElse node.Kind = BoundKind.Literal OrElse node.Kind = BoundKind.Parenthesized) Return True End If End If Return False End Function ''' <summary> ''' Return true if target BoundLiteral represents Nothing literal as defined by the language grammar. ''' </summary> <Extension()> Public Function IsNothingLiteral(node As BoundLiteral) As Boolean If node.Value.IsNothing Then Debug.Assert(node.Type Is Nothing) Return node.Type Is Nothing End If Return False End Function ''' <summary> ''' Return true if and only if an expression represents optionally ''' parenthesized Nothing literal as defined by the language grammar. ''' I.e. implicit conversions are Ok, but explicit conversions aren't. ''' </summary> <Extension()> Public Function IsStrictNothingLiteral(node As BoundExpression) As Boolean If Not IsNothingLiteral(node) Then Return False End If Dim constantValue As ConstantValue ' Dev10 treats parenthesized NOTHING as a literal. Do Select Case node.Kind Case BoundKind.Literal Return IsNothingLiteral(DirectCast(node, BoundLiteral)) Case BoundKind.Parenthesized Dim parenthesized = DirectCast(node, BoundParenthesized) node = parenthesized.Expression Case BoundKind.Conversion Dim conversion = DirectCast(node, BoundConversion) constantValue = conversion.ConstantValueOpt If Not (Not conversion.ExplicitCastInCode AndAlso constantValue IsNot Nothing AndAlso constantValue.IsNothing) Then Return False End If node = conversion.Operand Case Else Return False End Select Loop End Function <Extension()> Public Function GetMostEnclosedParenthesizedExpression(expression As BoundExpression) As BoundExpression While expression.Kind = BoundKind.Parenthesized expression = DirectCast(expression, BoundParenthesized).Expression End While Return expression End Function <Extension()> Public Function HasExpressionSymbols(node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.Call, BoundKind.Local, BoundKind.RangeVariable, BoundKind.FieldAccess, BoundKind.PropertyAccess, BoundKind.EventAccess, BoundKind.MethodGroup, BoundKind.PropertyGroup, BoundKind.ObjectCreationExpression, BoundKind.TypeExpression, BoundKind.NamespaceExpression, BoundKind.Conversion Return True Case BoundKind.BadExpression Return DirectCast(node, BoundBadExpression).Symbols.Length > 0 Case Else Return False End Select End Function <Extension()> Public Sub GetExpressionSymbols(methodGroup As BoundMethodGroup, symbols As ArrayBuilder(Of Symbol)) Dim targetArity As Integer = 0 If methodGroup.TypeArgumentsOpt IsNot Nothing Then targetArity = methodGroup.TypeArgumentsOpt.Arguments.Length End If For Each method In methodGroup.Methods ' This is a quick fix for the fact that binder lookup in VB does not perform arity check for ' method symbols leaving it to overload resolution code. Here we filter wrong arity methods If targetArity = 0 Then symbols.Add(method) ElseIf targetArity = method.Arity Then symbols.Add(method.Construct(methodGroup.TypeArgumentsOpt.Arguments)) End If Next ' Merge methodGroup.AdditionalExtensionMethods into the result. For Each method In methodGroup.AdditionalExtensionMethods(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) ' This is a quick fix for the fact that binder lookup in VB does not perform arity check for ' method symbols leaving it to overload resolution code. Here we filter wrong arity methods If targetArity = 0 Then symbols.Add(method) ElseIf targetArity = method.Arity Then symbols.Add(method.Construct(methodGroup.TypeArgumentsOpt.Arguments)) End If Next End Sub <Extension()> Public Sub GetExpressionSymbols(node As BoundExpression, symbols As ArrayBuilder(Of Symbol)) Select Case node.Kind Case BoundKind.MethodGroup DirectCast(node, BoundMethodGroup).GetExpressionSymbols(symbols) Case BoundKind.PropertyGroup symbols.AddRange(DirectCast(node, BoundPropertyGroup).Properties) Case BoundKind.BadExpression symbols.AddRange(DirectCast(node, BoundBadExpression).Symbols) Case BoundKind.QueryClause DirectCast(node, BoundQueryClause).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.AggregateClause DirectCast(node, BoundAggregateClause).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.Ordering DirectCast(node, BoundOrdering).UnderlyingExpression.GetExpressionSymbols(symbols) Case BoundKind.QuerySource DirectCast(node, BoundQuerySource).Expression.GetExpressionSymbols(symbols) Case BoundKind.ToQueryableCollectionConversion DirectCast(node, BoundToQueryableCollectionConversion).ConversionCall.GetExpressionSymbols(symbols) Case BoundKind.QueryableSource DirectCast(node, BoundQueryableSource).Source.GetExpressionSymbols(symbols) Case Else Dim symbol = node.ExpressionSymbol If symbol IsNot Nothing Then If symbol.Kind = SymbolKind.Namespace AndAlso DirectCast(symbol, NamespaceSymbol).NamespaceKind = NamespaceKindNamespaceGroup Then symbols.AddRange(DirectCast(symbol, NamespaceSymbol).ConstituentNamespaces) Else symbols.Add(symbol) End If End If End Select End Sub <Extension()> Public Function ToStatement(node As BoundExpression) As BoundExpressionStatement Return New BoundExpressionStatement(node.Syntax, node, node.HasErrors) End Function <Extension()> <Conditional("DEBUG")> Public Sub AssertRValue(node As BoundExpression) If Not node.HasErrors Then Debug.Assert(node.IsValue) Debug.Assert(Not node.IsLValue) Debug.Assert(Not node.IsPropertyOrXmlPropertyAccess() OrElse node.GetAccessKind() = PropertyAccessKind.Get) Debug.Assert(Not node.IsLateBound() OrElse node.GetLateBoundAccessKind() = LateBoundAccessKind.Get) Debug.Assert(If(node.Type Is Nothing, node.IsNothingLiteral() OrElse node.GetMostEnclosedParenthesizedExpression().Kind = BoundKind.AddressOfOperator OrElse node.GetMostEnclosedParenthesizedExpression().Kind = BoundKind.Lambda OrElse node.Kind = BoundKind.QueryLambda, Not node.Type.IsVoidType())) End If End Sub ''' <summary> ''' returns type arguments or Nothing if group does not have type arguments. ''' </summary> <Extension()> Friend Function TypeArguments(this As BoundMethodOrPropertyGroup) As BoundTypeArguments Dim asMethodGroup = TryCast(this, BoundMethodGroup) If asMethodGroup IsNot Nothing Then Return asMethodGroup.TypeArgumentsOpt End If Return Nothing End Function End Module End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Structure { internal abstract class BlockStructureServiceWithProviders : BlockStructureService { private readonly Workspace _workspace; private readonly ImmutableArray<BlockStructureProvider> _providers; protected BlockStructureServiceWithProviders(Workspace workspace) { _workspace = workspace; _providers = GetBuiltInProviders().Concat(GetImportedProviders()); } /// <summary> /// Returns the providers always available to the service. /// This does not included providers imported via MEF composition. /// </summary> protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders() => ImmutableArray<BlockStructureProvider>.Empty; private ImmutableArray<BlockStructureProvider> GetImportedProviders() { var language = Language; var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices; var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>() .Where(lz => lz.Metadata.Language == language) .Select(lz => lz.Value); return providers.ToImmutableArray(); } public override async Task<BlockStructure> GetBlockStructureAsync( Document document, CancellationToken cancellationToken) { var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false); return GetBlockStructure(context, _providers); } public BlockStructure GetBlockStructure( SyntaxTree syntaxTree, OptionSet options, bool isMetadataAsSource, CancellationToken cancellationToken) { var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); return GetBlockStructure(context, _providers); } private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var options = document.Project.Solution.Options; var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource; return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); } private static BlockStructureContext CreateContext( SyntaxTree syntaxTree, OptionSet options, bool isMetadataAsSource, CancellationToken cancellationToken) { var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource); return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken); } private static BlockStructure GetBlockStructure( BlockStructureContext context, ImmutableArray<BlockStructureProvider> providers) { foreach (var provider in providers) provider.ProvideBlockStructure(context); return CreateBlockStructure(context); } private static BlockStructure CreateBlockStructure(BlockStructureContext context) { var language = context.SyntaxTree.Options.Language; var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language); var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language); var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language); var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language); var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language); var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language); using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans); foreach (var span in context.Spans) { var updatedSpan = UpdateBlockSpan(span, showIndentGuidesForCodeLevelConstructs, showIndentGuidesForDeclarationLevelConstructs, showIndentGuidesForCommentsAndPreprocessorRegions, showOutliningForCodeLevelConstructs, showOutliningForDeclarationLevelConstructs, showOutliningForCommentsAndPreprocessorRegions); updatedSpans.Add(updatedSpan); } return new BlockStructure(updatedSpans.ToImmutable()); } private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan, bool showIndentGuidesForCodeLevelConstructs, bool showIndentGuidesForDeclarationLevelConstructs, bool showIndentGuidesForCommentsAndPreprocessorRegions, bool showOutliningForCodeLevelConstructs, bool showOutliningForDeclarationLevelConstructs, bool showOutliningForCommentsAndPreprocessorRegions) { var type = blockSpan.Type; var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type); var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type); var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type); if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) || (!showIndentGuidesForCodeLevelConstructs && isMemberLevel) || (!showIndentGuidesForCommentsAndPreprocessorRegions && isComment)) { type = BlockTypes.Nonstructural; } var isCollapsible = blockSpan.IsCollapsible; if (isCollapsible) { if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) || (!showOutliningForCodeLevelConstructs && isMemberLevel) || (!showOutliningForCommentsAndPreprocessorRegions && isComment)) { isCollapsible = false; } } return blockSpan.With(type: type, isCollapsible: isCollapsible); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Structure { internal abstract class BlockStructureServiceWithProviders : BlockStructureService { private readonly Workspace _workspace; private readonly ImmutableArray<BlockStructureProvider> _providers; protected BlockStructureServiceWithProviders(Workspace workspace) { _workspace = workspace; _providers = GetBuiltInProviders().Concat(GetImportedProviders()); } /// <summary> /// Returns the providers always available to the service. /// This does not included providers imported via MEF composition. /// </summary> protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders() => ImmutableArray<BlockStructureProvider>.Empty; private ImmutableArray<BlockStructureProvider> GetImportedProviders() { var language = Language; var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices; var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>() .Where(lz => lz.Metadata.Language == language) .Select(lz => lz.Value); return providers.ToImmutableArray(); } public override async Task<BlockStructure> GetBlockStructureAsync( Document document, CancellationToken cancellationToken) { var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false); return GetBlockStructure(context, _providers); } public BlockStructure GetBlockStructure( SyntaxTree syntaxTree, OptionSet options, bool isMetadataAsSource, CancellationToken cancellationToken) { var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); return GetBlockStructure(context, _providers); } private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var options = document.Project.Solution.Options; var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource; return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken); } private static BlockStructureContext CreateContext( SyntaxTree syntaxTree, OptionSet options, bool isMetadataAsSource, CancellationToken cancellationToken) { var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource); return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken); } private static BlockStructure GetBlockStructure( BlockStructureContext context, ImmutableArray<BlockStructureProvider> providers) { foreach (var provider in providers) provider.ProvideBlockStructure(context); return CreateBlockStructure(context); } private static BlockStructure CreateBlockStructure(BlockStructureContext context) { var language = context.SyntaxTree.Options.Language; var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language); var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language); var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language); var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language); var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language); var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language); using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans); foreach (var span in context.Spans) { var updatedSpan = UpdateBlockSpan(span, showIndentGuidesForCodeLevelConstructs, showIndentGuidesForDeclarationLevelConstructs, showIndentGuidesForCommentsAndPreprocessorRegions, showOutliningForCodeLevelConstructs, showOutliningForDeclarationLevelConstructs, showOutliningForCommentsAndPreprocessorRegions); updatedSpans.Add(updatedSpan); } return new BlockStructure(updatedSpans.ToImmutable()); } private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan, bool showIndentGuidesForCodeLevelConstructs, bool showIndentGuidesForDeclarationLevelConstructs, bool showIndentGuidesForCommentsAndPreprocessorRegions, bool showOutliningForCodeLevelConstructs, bool showOutliningForDeclarationLevelConstructs, bool showOutliningForCommentsAndPreprocessorRegions) { var type = blockSpan.Type; var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type); var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type); var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type); if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) || (!showIndentGuidesForCodeLevelConstructs && isMemberLevel) || (!showIndentGuidesForCommentsAndPreprocessorRegions && isComment)) { type = BlockTypes.Nonstructural; } var isCollapsible = blockSpan.IsCollapsible; if (isCollapsible) { if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) || (!showOutliningForCodeLevelConstructs && isMemberLevel) || (!showOutliningForCommentsAndPreprocessorRegions && isComment)) { isCollapsible = false; } } return blockSpan.With(type: type, isCollapsible: isCollapsible); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Dependencies/Collections/Internal/ArraySortHelper.cs
// Licensed to the .NET Foundation under one or more 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/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.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.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; #if NETCOREAPP using System.Numerics; #else using System.Runtime.InteropServices; #endif #if !NET5_0 && !NET5_0_OR_GREATER using Half = System.Single; #endif namespace Microsoft.CodeAnalysis.Collections.Internal { #region ArraySortHelper for single arrays internal static class SegmentedArraySortHelper<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } internal static void Sort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer!); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(SegmentedArraySegment<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer!, 0, 1); SwapIfGreater(keys, comparer!, 0, 2); SwapIfGreater(keys, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer!, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer!, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer!, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal static class SegmentedGenericArraySortHelper<T> where T : IComparable<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return SegmentedArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(SegmentedArray<T> array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value!); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. int zeroIndex = 0; int lastIndex = keys.Length - 1; int middleIndex = (keys.Length - 1) >> 1; SwapIfGreater(ref keys[zeroIndex], ref keys[middleIndex]); SwapIfGreater(ref keys[zeroIndex], ref keys[lastIndex]); SwapIfGreater(ref keys[middleIndex], ref keys[lastIndex]); // Select the middle value as the pivot, and move it to be just before the last element. int nextToLastIndex = keys.Length - 2; T pivot = keys[middleIndex]; Swap(ref keys[middleIndex], ref keys[nextToLastIndex]); // Walk the left and right pointers, swapping elements as necessary, until they cross. int leftIndex = zeroIndex, rightIndex = nextToLastIndex; while (leftIndex < rightIndex) { if (pivot == null) { while (leftIndex < nextToLastIndex && keys[++leftIndex] == null) { // Intentionally empty } while (rightIndex > zeroIndex && keys[--rightIndex] != null) { // Intentionally empty } } else { while (leftIndex < nextToLastIndex && GreaterThan(ref pivot, ref keys[++leftIndex])) { // Intentionally empty } while (rightIndex > zeroIndex && LessThan(ref pivot, ref keys[--rightIndex])) { // Intentionally empty } } if (leftIndex >= rightIndex) { break; } Swap(ref keys[leftIndex], ref keys[rightIndex]); } // Put the pivot in the correct location. if (leftIndex != nextToLastIndex) { Swap(ref keys[leftIndex], ref keys[nextToLastIndex]); } return leftIndex; } private static void HeapSort(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal static class SegmentedArraySortHelper<TKey, TValue> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer!.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); SwapIfGreaterWithValues(keys, values, comparer!, 0, 2); SwapIfGreaterWithValues(keys, values, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer!, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer!, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer!, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!.Compare(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer.Compare(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer!.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal static class SegmentedGenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) { // Intentionally empty } while (right > 0 && keys[--right] != null) { // Intentionally empty } } else { while (GreaterThan(ref pivot, ref keys[++left])) { // Intentionally empty } while (LessThan(ref pivot, ref keys[--right])) { // Intentionally empty } } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SegmentedArraySortUtils { #if !NETCOREAPP private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 00, 09, 01, 10, 13, 21, 02, 29, 11, 14, 16, 18, 22, 25, 03, 30, 08, 12, 20, 28, 15, 17, 24, 07, 19, 27, 23, 06, 26, 05, 04, 31, }; #endif public static int MoveNansToFront<TKey, TValue>(SegmentedArraySegment<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } public static int Log2(uint value) { #if NETCOREAPP return BitOperations.Log2(value); #else // Fallback contract is 0->0 return Log2SoftwareFallback(value); #endif } #if !NETCOREAPP /// <summary> /// Returns the integer (floor) log of the specified value, base 2. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined. /// Does not directly use any hardware intrinsics, nor does it incur branching. /// </summary> /// <param name="value">The value.</param> private static int Log2SoftwareFallback(uint value) { // No AggressiveInlining due to large method size // Has conventional contract 0->0 (Log(0) is undefined) // Fill trailing zeros with ones, eg 00010010 becomes 00011111 value |= value >> 01; value |= value >> 02; value |= value >> 04; value |= value >> 08; value |= value >> 16; // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check return Unsafe.AddByteOffset( // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u ref MemoryMarshal.GetReference(Log2DeBruijn), // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here (IntPtr)(int)((value * 0x07C4ACDDu) >> 27)); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.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.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; #if NETCOREAPP using System.Numerics; #else using System.Runtime.InteropServices; #endif #if !NET5_0 && !NET5_0_OR_GREATER using Half = System.Single; #endif namespace Microsoft.CodeAnalysis.Collections.Internal { #region ArraySortHelper for single arrays internal static class SegmentedArraySortHelper<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { comparer ??= Comparer<T>.Default; IntrospectiveSort(keys, comparer.Compare); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { try { comparer ??= Comparer<T>.Default; return InternalBinarySearch(array, index, length, value, comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } internal static void Sort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null, "Check the arguments in the caller!"); // Add a try block here to detect bogus comparisons try { IntrospectiveSort(keys, comparer!); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } internal static int InternalBinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T> comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(array[i], value); if (order == 0) return i; if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private static void SwapIfGreater(SegmentedArraySegment<T> keys, Comparison<T> comparer, int i, int j) { Debug.Assert(i != j); if (comparer(keys[i], keys[j]) > 0) { T key = keys[i]; keys[i] = keys[j]; keys[j] = key; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<T> a, int i, int j) { Debug.Assert(i != j); T t = a[i]; a[i] = a[j]; a[j] = t; } internal static void IntrospectiveSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); if (keys.Length > 1) { IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit, Comparison<T> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(keys, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreater(keys, comparer!, 0, 1); SwapIfGreater(keys, comparer!, 0, 2); SwapIfGreater(keys, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreater(keys, comparer!, 0, middle); // swap the low with the mid point SwapIfGreater(keys, comparer!, 0, hi); // swap the low with the high SwapIfGreater(keys, comparer!, middle, hi); // swap the middle with the high T pivot = keys[middle]; Swap(keys, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, 0, i - 1); DownHeap(keys, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo, Comparison<T> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys, Comparison<T> comparer) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && comparer(t, keys[j]) < 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t; } } } internal static class SegmentedGenericArraySortHelper<T> where T : IComparable<T> { public static void Sort(SegmentedArraySegment<T> keys, IComparer<T>? comparer) { try { if (comparer == null || comparer == Comparer<T>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(T) == typeof(double) || typeof(T) == typeof(float) || typeof(T) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, default(Span<byte>)); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); } IntroSort(keys, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<T>.IntrospectiveSort(keys, comparer.Compare); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } public static int BinarySearch(SegmentedArray<T> array, int index, int length, T value, IComparer<T>? comparer) { Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); try { if (comparer == null || comparer == Comparer<T>.Default) { return BinarySearch(array, index, length, value); } else { return SegmentedArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer); } } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } } // This function is called when the user doesn't specify any comparer. // Since T is constrained here, we can call IComparable<T>.CompareTo here. // We can avoid boxing for value type and casting for reference types. private static int BinarySearch(SegmentedArray<T> array, int index, int length, T value) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order; if (array[i] == null) { order = (value == null) ? 0 : -1; } else { order = array[i].CompareTo(value!); } if (order == 0) { return i; } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } /// <summary>Swaps the values in the two references if the first is greater than the second.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SwapIfGreater(ref T i, ref T j) { if (i != null && GreaterThan(ref i, ref j)) { Swap(ref i, ref j); } } /// <summary>Swaps the values in the two references, regardless of whether the two references are the same.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(ref T i, ref T j) { Debug.Assert(!Unsafe.AreSame(ref i, ref j)); T t = i; i = j; j = t; } private static void IntroSort(SegmentedArraySegment<T> keys, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreater(ref keys[0], ref keys[1]); return; } if (partitionSize == 3) { ref T hiRef = ref keys[2]; ref T him1Ref = ref keys[1]; ref T loRef = ref keys[0]; SwapIfGreater(ref loRef, ref him1Ref); SwapIfGreater(ref loRef, ref hiRef); SwapIfGreater(ref him1Ref, ref hiRef); return; } InsertionSort(keys.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); // Use median-of-three to select a pivot. Grab a reference to the 0th, Length-1th, and Length/2th elements, and sort them. int zeroIndex = 0; int lastIndex = keys.Length - 1; int middleIndex = (keys.Length - 1) >> 1; SwapIfGreater(ref keys[zeroIndex], ref keys[middleIndex]); SwapIfGreater(ref keys[zeroIndex], ref keys[lastIndex]); SwapIfGreater(ref keys[middleIndex], ref keys[lastIndex]); // Select the middle value as the pivot, and move it to be just before the last element. int nextToLastIndex = keys.Length - 2; T pivot = keys[middleIndex]; Swap(ref keys[middleIndex], ref keys[nextToLastIndex]); // Walk the left and right pointers, swapping elements as necessary, until they cross. int leftIndex = zeroIndex, rightIndex = nextToLastIndex; while (leftIndex < rightIndex) { if (pivot == null) { while (leftIndex < nextToLastIndex && keys[++leftIndex] == null) { // Intentionally empty } while (rightIndex > zeroIndex && keys[--rightIndex] != null) { // Intentionally empty } } else { while (leftIndex < nextToLastIndex && GreaterThan(ref pivot, ref keys[++leftIndex])) { // Intentionally empty } while (rightIndex > zeroIndex && LessThan(ref pivot, ref keys[--rightIndex])) { // Intentionally empty } } if (leftIndex >= rightIndex) { break; } Swap(ref keys[leftIndex], ref keys[rightIndex]); } // Put the pivot in the correct location. if (leftIndex != nextToLastIndex) { Swap(ref keys[leftIndex], ref keys[nextToLastIndex]); } return leftIndex; } private static void HeapSort(SegmentedArraySegment<T> keys) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, i, n, 0); } for (int i = n; i > 1; i--) { Swap(ref keys[0], ref keys[i - 1]); DownHeap(keys, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<T> keys, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); T d = keys[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; i = child; } keys[lo + i - 1] = d; } private static void InsertionSort(SegmentedArraySegment<T> keys) { for (int i = 0; i < keys.Length - 1; i++) { T t = keys[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = t!; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref T left, ref T right) { if (typeof(T) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(T) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(T) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(T) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(T) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(T) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(T) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(T) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(T) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(T) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(T) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(T) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(T) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion #region ArraySortHelper for paired key and value arrays internal static class SegmentedArraySortHelper<TKey, TValue> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { IntrospectiveSort(keys, values, comparer ?? Comparer<TKey>.Default); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer, int i, int j) { Debug.Assert(comparer != null); Debug.Assert(0 <= i && i < keys.Length && i < values.Length); Debug.Assert(0 <= j && j < keys.Length && j < values.Length); Debug.Assert(i != j); if (comparer!.Compare(keys[i], keys[j]) > 0) { TKey key = keys[i]; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } internal static void IntrospectiveSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length == values.Length); if (keys.Length > 1) { IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1), comparer!); } } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit, IComparer<TKey> comparer) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); Debug.Assert(comparer != null); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, comparer!, 0, 1); SwapIfGreaterWithValues(keys, values, comparer!, 0, 2); SwapIfGreaterWithValues(keys, values, comparer!, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize), comparer!); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit, comparer!); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); Debug.Assert(comparer != null); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, comparer!, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, comparer!, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, comparer!, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { while (comparer!.Compare(keys[++left], pivot) < 0) { // Intentionally empty } while (comparer.Compare(pivot, keys[--right]) < 0) { // Intentionally empty } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0, comparer!); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0, comparer!); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo, IComparer<TKey> comparer) { Debug.Assert(comparer != null); Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && comparer!.Compare(keys[lo + child - 1], keys[lo + child]) < 0) { child++; } if (!(comparer!.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey> comparer) { Debug.Assert(comparer != null); for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && comparer!.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t; values[j + 1] = tValue; } } } internal static class SegmentedGenericArraySortHelper<TKey, TValue> where TKey : IComparable<TKey> { public static void Sort(SegmentedArraySegment<TKey> keys, Span<TValue> values, IComparer<TKey>? comparer) { // Add a try block here to detect IComparers (or their // underlying IComparables, etc) that are bogus. try { if (comparer == null || comparer == Comparer<TKey>.Default) { if (keys.Length > 1) { // For floating-point, do a pre-pass to move all NaNs to the beginning // so that we can do an optimized comparison as part of the actual sort // on the remainder of the values. if (typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float) || typeof(TKey) == typeof(Half)) { int nanLeft = SegmentedArraySortUtils.MoveNansToFront(keys, values); if (nanLeft == keys.Length) { return; } keys = keys.Slice(nanLeft); values = values.Slice(nanLeft); } IntroSort(keys, values, 2 * (SegmentedArraySortUtils.Log2((uint)keys.Length) + 1)); } } else { SegmentedArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, comparer); } } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private static void SwapIfGreaterWithValues(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); ref TKey keyRef = ref keys[i]; if (keyRef != null && GreaterThan(ref keyRef, ref keys[j])) { TKey key = keyRef; keys[i] = keys[j]; keys[j] = key; TValue value = values[i]; values[i] = values[j]; values[j] = value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Swap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int j) { Debug.Assert(i != j); TKey k = keys[i]; keys[i] = keys[j]; keys[j] = k; TValue v = values[i]; values[i] = values[j]; values[j] = v; } private static void IntroSort(SegmentedArraySegment<TKey> keys, Span<TValue> values, int depthLimit) { Debug.Assert(keys.Length > 0); Debug.Assert(values.Length == keys.Length); Debug.Assert(depthLimit >= 0); int partitionSize = keys.Length; while (partitionSize > 1) { if (partitionSize <= SegmentedArrayHelper.IntrosortSizeThreshold) { if (partitionSize == 2) { SwapIfGreaterWithValues(keys, values, 0, 1); return; } if (partitionSize == 3) { SwapIfGreaterWithValues(keys, values, 0, 1); SwapIfGreaterWithValues(keys, values, 0, 2); SwapIfGreaterWithValues(keys, values, 1, 2); return; } InsertionSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } if (depthLimit == 0) { HeapSort(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); return; } depthLimit--; int p = PickPivotAndPartition(keys.Slice(0, partitionSize), values.Slice(0, partitionSize)); // Note we've already partitioned around the pivot and do not have to move the pivot again. IntroSort(keys.Slice(p + 1, partitionSize - (p + 1)), values.Slice(p + 1, partitionSize - (p + 1)), depthLimit); partitionSize = p; } } private static int PickPivotAndPartition(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length >= SegmentedArrayHelper.IntrosortSizeThreshold); int hi = keys.Length - 1; // Compute median-of-three. But also partition them, since we've done the comparison. int middle = hi >> 1; // Sort lo, mid and hi appropriately, then pick mid as the pivot. SwapIfGreaterWithValues(keys, values, 0, middle); // swap the low with the mid point SwapIfGreaterWithValues(keys, values, 0, hi); // swap the low with the high SwapIfGreaterWithValues(keys, values, middle, hi); // swap the middle with the high TKey pivot = keys[middle]; Swap(keys, values, middle, hi - 1); int left = 0, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. while (left < right) { if (pivot == null) { while (left < (hi - 1) && keys[++left] == null) { // Intentionally empty } while (right > 0 && keys[--right] != null) { // Intentionally empty } } else { while (GreaterThan(ref pivot, ref keys[++left])) { // Intentionally empty } while (LessThan(ref pivot, ref keys[--right])) { // Intentionally empty } } if (left >= right) break; Swap(keys, values, left, right); } // Put pivot in the right location. if (left != hi - 1) { Swap(keys, values, left, hi - 1); } return left; } private static void HeapSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { Debug.Assert(keys.Length > 0); int n = keys.Length; for (int i = n >> 1; i >= 1; i--) { DownHeap(keys, values, i, n, 0); } for (int i = n; i > 1; i--) { Swap(keys, values, 0, i - 1); DownHeap(keys, values, 1, i - 1, 0); } } private static void DownHeap(SegmentedArraySegment<TKey> keys, Span<TValue> values, int i, int n, int lo) { Debug.Assert(lo >= 0); Debug.Assert(lo < keys.Length); TKey d = keys[lo + i - 1]; TValue dValue = values[lo + i - 1]; while (i <= n >> 1) { int child = 2 * i; if (child < n && (keys[lo + child - 1] == null || LessThan(ref keys[lo + child - 1], ref keys[lo + child]))) { child++; } if (keys[lo + child - 1] == null || !LessThan(ref d, ref keys[lo + child - 1])) break; keys[lo + i - 1] = keys[lo + child - 1]; values[lo + i - 1] = values[lo + child - 1]; i = child; } keys[lo + i - 1] = d; values[lo + i - 1] = dValue; } private static void InsertionSort(SegmentedArraySegment<TKey> keys, Span<TValue> values) { for (int i = 0; i < keys.Length - 1; i++) { TKey t = keys[i + 1]; TValue tValue = values[i + 1]; int j = i; while (j >= 0 && (t == null || LessThan(ref t, ref keys[j]))) { keys[j + 1] = keys[j]; values[j + 1] = values[j]; j--; } keys[j + 1] = t!; values[j + 1] = tValue; } } // - These methods exist for use in sorting, where the additional operations present in // the CompareTo methods that would otherwise be used on these primitives add non-trivial overhead, // in particular for floating point where the CompareTo methods need to factor in NaNs. // - The floating-point comparisons here assume no NaNs, which is valid only because the sorting routines // themselves special-case NaN with a pre-pass that ensures none are present in the values being sorted // by moving them all to the front first and then sorting the rest. // - The `? true : false` is to work-around poor codegen: https://github.com/dotnet/runtime/issues/37904#issuecomment-644180265. // - These are duplicated here rather than being on a helper type due to current limitations around generic inlining. [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool LessThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left < (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left < (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left < (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left < (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left < (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left < (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left < (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left < (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left < (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left < (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left < (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left < (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left < (Half)(object)right ? true : false; return left.CompareTo(right) < 0 ? true : false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single comparison or method call private static bool GreaterThan(ref TKey left, ref TKey right) { if (typeof(TKey) == typeof(byte)) return (byte)(object)left > (byte)(object)right ? true : false; if (typeof(TKey) == typeof(sbyte)) return (sbyte)(object)left > (sbyte)(object)right ? true : false; if (typeof(TKey) == typeof(ushort)) return (ushort)(object)left > (ushort)(object)right ? true : false; if (typeof(TKey) == typeof(short)) return (short)(object)left > (short)(object)right ? true : false; if (typeof(TKey) == typeof(uint)) return (uint)(object)left > (uint)(object)right ? true : false; if (typeof(TKey) == typeof(int)) return (int)(object)left > (int)(object)right ? true : false; if (typeof(TKey) == typeof(ulong)) return (ulong)(object)left > (ulong)(object)right ? true : false; if (typeof(TKey) == typeof(long)) return (long)(object)left > (long)(object)right ? true : false; if (typeof(TKey) == typeof(UIntPtr)) return (nuint)(object)left > (nuint)(object)right ? true : false; if (typeof(TKey) == typeof(IntPtr)) return (nint)(object)left > (nint)(object)right ? true : false; if (typeof(TKey) == typeof(float)) return (float)(object)left > (float)(object)right ? true : false; if (typeof(TKey) == typeof(double)) return (double)(object)left > (double)(object)right ? true : false; if (typeof(TKey) == typeof(Half)) return (Half)(object)left > (Half)(object)right ? true : false; return left.CompareTo(right) > 0 ? true : false; } } #endregion /// <summary>Helper methods for use in array/span sorting routines.</summary> internal static class SegmentedArraySortUtils { #if !NETCOREAPP private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32] { 00, 09, 01, 10, 13, 21, 02, 29, 11, 14, 16, 18, 22, 25, 03, 30, 08, 12, 20, 28, 15, 17, 24, 07, 19, 27, 23, 06, 26, 05, 04, 31, }; #endif public static int MoveNansToFront<TKey, TValue>(SegmentedArraySegment<TKey> keys, Span<TValue> values) where TKey : notnull { Debug.Assert(typeof(TKey) == typeof(double) || typeof(TKey) == typeof(float)); int left = 0; for (int i = 0; i < keys.Length; i++) { if ((typeof(TKey) == typeof(double) && double.IsNaN((double)(object)keys[i])) || (typeof(TKey) == typeof(float) && float.IsNaN((float)(object)keys[i])) || (typeof(TKey) == typeof(Half) && Half.IsNaN((Half)(object)keys[i]))) { TKey temp = keys[left]; keys[left] = keys[i]; keys[i] = temp; if ((uint)i < (uint)values.Length) // check to see if we have values { TValue tempValue = values[left]; values[left] = values[i]; values[i] = tempValue; } left++; } } return left; } public static int Log2(uint value) { #if NETCOREAPP return BitOperations.Log2(value); #else // Fallback contract is 0->0 return Log2SoftwareFallback(value); #endif } #if !NETCOREAPP /// <summary> /// Returns the integer (floor) log of the specified value, base 2. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined. /// Does not directly use any hardware intrinsics, nor does it incur branching. /// </summary> /// <param name="value">The value.</param> private static int Log2SoftwareFallback(uint value) { // No AggressiveInlining due to large method size // Has conventional contract 0->0 (Log(0) is undefined) // Fill trailing zeros with ones, eg 00010010 becomes 00011111 value |= value >> 01; value |= value >> 02; value |= value >> 04; value |= value >> 08; value |= value >> 16; // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check return Unsafe.AddByteOffset( // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u ref MemoryMarshal.GetReference(Log2DeBruijn), // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here (IntPtr)(int)((value * 0x07C4ACDDu) >> 27)); } #endif } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Test/SymbolFinder/FindSymbolAtPositionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { [UseExportProvider] public class FindSymbolAtPositionTests { private static Task<ISymbol> FindSymbolAtPositionAsync(TestWorkspace workspace) { var position = workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition!.Value; var document = workspace.CurrentSolution.GetRequiredDocument(workspace.Documents.Single().Id); return SymbolFinder.FindSymbolAtPositionAsync(document, position); } [Fact] public async Task PositionOnLeadingTrivia() { using var workspace = TestWorkspace.CreateCSharp( @"using System; class Program { static void Main() { $$#pragma warning disable 612 Goo(); #pragma warning restore 612 } }"); var symbol = await FindSymbolAtPositionAsync(workspace); Assert.Null(symbol); } [Fact] [WorkItem(53269, "https://github.com/dotnet/roslyn/issues/53269")] public async Task PositionInCaseLabel() { using var workspace = TestWorkspace.CreateCSharp( @"using System; enum E { A, B } class Program { static void Main() { E e = default; switch (e) { case E.$$A: break; } } }"); var fieldSymbol = Assert.IsAssignableFrom<IFieldSymbol>(await FindSymbolAtPositionAsync(workspace)); Assert.Equal(TypeKind.Enum, fieldSymbol.ContainingType.TypeKind); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { [UseExportProvider] public class FindSymbolAtPositionTests { private static Task<ISymbol> FindSymbolAtPositionAsync(TestWorkspace workspace) { var position = workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition!.Value; var document = workspace.CurrentSolution.GetRequiredDocument(workspace.Documents.Single().Id); return SymbolFinder.FindSymbolAtPositionAsync(document, position); } [Fact] public async Task PositionOnLeadingTrivia() { using var workspace = TestWorkspace.CreateCSharp( @"using System; class Program { static void Main() { $$#pragma warning disable 612 Goo(); #pragma warning restore 612 } }"); var symbol = await FindSymbolAtPositionAsync(workspace); Assert.Null(symbol); } [Fact] [WorkItem(53269, "https://github.com/dotnet/roslyn/issues/53269")] public async Task PositionInCaseLabel() { using var workspace = TestWorkspace.CreateCSharp( @"using System; enum E { A, B } class Program { static void Main() { E e = default; switch (e) { case E.$$A: break; } } }"); var fieldSymbol = Assert.IsAssignableFrom<IFieldSymbol>(await FindSymbolAtPositionAsync(workspace)); Assert.Equal(TypeKind.Enum, fieldSymbol.ContainingType.TypeKind); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.MSBuild.Logging; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal abstract class ProjectFileLoader : IProjectFileLoader { public abstract string Language { get; } protected abstract ProjectFile CreateProjectFile(MSB.Evaluation.Project? project, ProjectBuildManager buildManager, DiagnosticLog log); public async Task<IProjectFile> LoadProjectFileAsync(string path, ProjectBuildManager buildManager, CancellationToken cancellationToken) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // load project file async var (project, log) = await buildManager.LoadProjectAsync(path, cancellationToken).ConfigureAwait(false); return this.CreateProjectFile(project, buildManager, log); } public static IProjectFileLoader GetLoaderForProjectFileExtension(HostWorkspaceServices workspaceServices, string extension) { return workspaceServices.FindLanguageServices<IProjectFileLoader>( d => d.GetEnumerableMetadata<string>("ProjectFileExtension").Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase))) .FirstOrDefault(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.MSBuild.Logging; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal abstract class ProjectFileLoader : IProjectFileLoader { public abstract string Language { get; } protected abstract ProjectFile CreateProjectFile(MSB.Evaluation.Project? project, ProjectBuildManager buildManager, DiagnosticLog log); public async Task<IProjectFile> LoadProjectFileAsync(string path, ProjectBuildManager buildManager, CancellationToken cancellationToken) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // load project file async var (project, log) = await buildManager.LoadProjectAsync(path, cancellationToken).ConfigureAwait(false); return this.CreateProjectFile(project, buildManager, log); } public static IProjectFileLoader GetLoaderForProjectFileExtension(HostWorkspaceServices workspaceServices, string extension) { return workspaceServices.FindLanguageServices<IProjectFileLoader>( d => d.GetEnumerableMetadata<string>("ProjectFileExtension").Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase))) .FirstOrDefault(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/CSharp/Portable/GoToDefinition/CSharpFindDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.CSharp), Shared] internal class CSharpFindDefinitionService : AbstractFindDefinitionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindDefinitionService() { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.CSharp), Shared] internal class CSharpFindDefinitionService : AbstractFindDefinitionService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpFindDefinitionService() { } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Test/Emit/PDB/PDBTupleTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBTupleTests : CSharpPDBTestBase { [Fact] public void Local() { var source = WithWindowsLineBreaks( @"class C { static void F() { (int A, int B, (int C, int), int, int, int G, int H, int I) t = (1, 2, (3, 4), 5, 6, 7, 8, 9); } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|A|B||||G|H|I|C||"" slotIndex=""0"" localName=""t"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""71"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""103"" document=""1"" /> <entry offset=""0x1b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void Constant() { var source = WithWindowsLineBreaks( @"class C<T> { static (int, int) F; } class C { static void F() { const C<(int A, int B)> c = null; } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|A|B"" slotIndex=""-1"" localName=""c"" scopeStart=""0x0"" scopeEnd=""0x2"" /> </tupleElementNames> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""c"" value=""null"" signature=""C`1{System.ValueTuple`2{Int32, Int32}}"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TuplesAndDynamic() { var source = WithWindowsLineBreaks( @"class C<T> { } class C { static void F() { { (dynamic A, object B, object)[] x; const C<(object, dynamic, object C)> y = null; } { const C<(object A, object)> x = null; } { const C<(object, dynamic)> x = null; const C<(object, dynamic B)> y = null; } } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""00100"" slotId=""0"" localName=""x"" /> <bucket flags=""00010"" slotId=""0"" localName=""y"" /> <bucket flags=""0001"" slotId=""0"" localName=""x"" /> <bucket flags=""0001"" slotId=""0"" localName=""y"" /> </dynamicLocals> <tupleElementNames> <local elementNames=""|A|B|"" slotIndex=""0"" localName=""x"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|||C"" slotIndex=""-1"" localName=""y"" scopeStart=""0x1"" scopeEnd=""0x3"" /> <local elementNames=""|A|"" slotIndex=""-1"" localName=""x"" scopeStart=""0x3"" scopeEnd=""0x5"" /> <local elementNames=""||B"" slotIndex=""-1"" localName=""y"" scopeStart=""0x5"" scopeEnd=""0x7"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <scope startOffset=""0x1"" endOffset=""0x3""> <local name=""x"" il_index=""0"" il_start=""0x1"" il_end=""0x3"" attributes=""0"" /> <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`3{Object, Object, Object}}"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> </scope> <scope startOffset=""0x5"" endOffset=""0x7""> <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void MultiByteCharacters() { var source = WithWindowsLineBreaks( @"class C { static void F() { (int \u1234, int, int \u005f\u1200\u005f) \u1200 = (1, 2, 3); } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( string.Format(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|{0}||{1}"" slotIndex=""0"" localName=""{2}"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""53"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""70"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""{2}"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols>", "\u1234", "_\u1200_", "\u1200")); } [Fact] public void DeconstructionForeach() { var source = WithWindowsLineBreaks( @"class C { static void F(System.Collections.Generic.IEnumerable<(int a, int b)> ie) { //4,5 foreach ( //5,9 var (a, b) //6,13 in //7,13 ie) //8,13 { //9,9 } //10,9 } //11,5 }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( string.Format(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""ie""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""5"" offset=""17"" /> <slot kind=""0"" offset=""59"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""15"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0xb"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x36""> <scope startOffset=""0xb"" endOffset=""0x20""> <local name=""a"" il_index=""1"" il_start=""0xb"" il_end=""0x20"" attributes=""0"" /> <local name=""b"" il_index=""2"" il_start=""0xb"" il_end=""0x20"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>")); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { (int a, int b)[] v1 = null; const (int a, int b)[] c1 = null; throw null; (int a, int b)[] v2 = null; const (int a, int b)[] c2 = null; { (int a, int b)[] v3 = null; const (int a, int b)[] c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 5 (0x5) .maxstack 1 .locals init (System.ValueTuple<int, int>[] V_0, //v1 System.ValueTuple<int, int>[] V_1, //v2 System.ValueTuple<int, int>[] V_2) //v3 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldnull IL_0004: throw } "); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|a|b"" slotIndex=""0"" localName=""v1"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|a|b"" slotIndex=""1"" localName=""v2"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c1"" scopeStart=""0x0"" scopeEnd=""0x5"" /> <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c2"" scopeStart=""0x0"" scopeEnd=""0x5"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""28"" /> <slot kind=""0"" offset=""133"" /> <slot kind=""0"" offset=""232"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""36"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x5""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" /> <constant name=""c1"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" /> <constant name=""c2"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" /> </scope> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBTupleTests : CSharpPDBTestBase { [Fact] public void Local() { var source = WithWindowsLineBreaks( @"class C { static void F() { (int A, int B, (int C, int), int, int, int G, int H, int I) t = (1, 2, (3, 4), 5, 6, 7, 8, 9); } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|A|B||||G|H|I|C||"" slotIndex=""0"" localName=""t"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""71"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""103"" document=""1"" /> <entry offset=""0x1b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void Constant() { var source = WithWindowsLineBreaks( @"class C<T> { static (int, int) F; } class C { static void F() { const C<(int A, int B)> c = null; } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|A|B"" slotIndex=""-1"" localName=""c"" scopeStart=""0x0"" scopeEnd=""0x2"" /> </tupleElementNames> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""c"" value=""null"" signature=""C`1{System.ValueTuple`2{Int32, Int32}}"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TuplesAndDynamic() { var source = WithWindowsLineBreaks( @"class C<T> { } class C { static void F() { { (dynamic A, object B, object)[] x; const C<(object, dynamic, object C)> y = null; } { const C<(object A, object)> x = null; } { const C<(object, dynamic)> x = null; const C<(object, dynamic B)> y = null; } } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""00100"" slotId=""0"" localName=""x"" /> <bucket flags=""00010"" slotId=""0"" localName=""y"" /> <bucket flags=""0001"" slotId=""0"" localName=""x"" /> <bucket flags=""0001"" slotId=""0"" localName=""y"" /> </dynamicLocals> <tupleElementNames> <local elementNames=""|A|B|"" slotIndex=""0"" localName=""x"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|||C"" slotIndex=""-1"" localName=""y"" scopeStart=""0x1"" scopeEnd=""0x3"" /> <local elementNames=""|A|"" slotIndex=""-1"" localName=""x"" scopeStart=""0x3"" scopeEnd=""0x5"" /> <local elementNames=""||B"" slotIndex=""-1"" localName=""y"" scopeStart=""0x5"" scopeEnd=""0x7"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <scope startOffset=""0x1"" endOffset=""0x3""> <local name=""x"" il_index=""0"" il_start=""0x1"" il_end=""0x3"" attributes=""0"" /> <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`3{Object, Object, Object}}"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> </scope> <scope startOffset=""0x5"" endOffset=""0x7""> <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void MultiByteCharacters() { var source = WithWindowsLineBreaks( @"class C { static void F() { (int \u1234, int, int \u005f\u1200\u005f) \u1200 = (1, 2, 3); } }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( string.Format(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|{0}||{1}"" slotIndex=""0"" localName=""{2}"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""53"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""70"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""{2}"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols>", "\u1234", "_\u1200_", "\u1200")); } [Fact] public void DeconstructionForeach() { var source = WithWindowsLineBreaks( @"class C { static void F(System.Collections.Generic.IEnumerable<(int a, int b)> ie) { //4,5 foreach ( //5,9 var (a, b) //6,13 in //7,13 ie) //8,13 { //9,9 } //10,9 } //11,5 }"); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb( string.Format(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""ie""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""5"" offset=""17"" /> <slot kind=""0"" offset=""59"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""15"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0xb"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x36""> <scope startOffset=""0xb"" endOffset=""0x20""> <local name=""a"" il_index=""1"" il_start=""0xb"" il_end=""0x20"" attributes=""0"" /> <local name=""b"" il_index=""2"" il_start=""0xb"" il_end=""0x20"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>")); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { (int a, int b)[] v1 = null; const (int a, int b)[] c1 = null; throw null; (int a, int b)[] v2 = null; const (int a, int b)[] c2 = null; { (int a, int b)[] v3 = null; const (int a, int b)[] c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 5 (0x5) .maxstack 1 .locals init (System.ValueTuple<int, int>[] V_0, //v1 System.ValueTuple<int, int>[] V_1, //v2 System.ValueTuple<int, int>[] V_2) //v3 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldnull IL_0004: throw } "); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|a|b"" slotIndex=""0"" localName=""v1"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|a|b"" slotIndex=""1"" localName=""v2"" scopeStart=""0x0"" scopeEnd=""0x0"" /> <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c1"" scopeStart=""0x0"" scopeEnd=""0x5"" /> <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c2"" scopeStart=""0x0"" scopeEnd=""0x5"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""28"" /> <slot kind=""0"" offset=""133"" /> <slot kind=""0"" offset=""232"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""36"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x5""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" /> <constant name=""c1"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" /> <constant name=""c2"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" /> </scope> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.Analyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { internal partial class CSharpAsAndNullCheckDiagnosticAnalyzer { private readonly struct Analyzer { private readonly SemanticModel _semanticModel; private readonly ILocalSymbol _localSymbol; private readonly ExpressionSyntax _comparison; private readonly ExpressionSyntax _operand; private readonly SyntaxNode _localStatement; private readonly SyntaxNode _enclosingBlock; private readonly CancellationToken _cancellationToken; private Analyzer( SemanticModel semanticModel, ILocalSymbol localSymbol, ExpressionSyntax comparison, ExpressionSyntax operand, SyntaxNode localStatement, SyntaxNode enclosingBlock, CancellationToken cancellationToken) { Debug.Assert(semanticModel != null); Debug.Assert(localSymbol != null); Debug.Assert(comparison != null); Debug.Assert(operand != null); Debug.Assert(localStatement.IsKind(SyntaxKind.LocalDeclarationStatement)); Debug.Assert(enclosingBlock.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection)); _semanticModel = semanticModel; _comparison = comparison; _localSymbol = localSymbol; _operand = operand; _localStatement = localStatement; _enclosingBlock = enclosingBlock; _cancellationToken = cancellationToken; } public static bool CanSafelyConvertToPatternMatching( SemanticModel semanticModel, ILocalSymbol localSymbol, ExpressionSyntax comparison, ExpressionSyntax operand, SyntaxNode localStatement, SyntaxNode enclosingBlock, CancellationToken cancellationToken) { var analyzer = new Analyzer(semanticModel, localSymbol, comparison, operand, localStatement, enclosingBlock, cancellationToken); return analyzer.CanSafelyConvertToPatternMatching(); } // To convert a null-check to pattern-matching, we should make sure of a few things: // // (1) The pattern variable may not be used before the point of declaration. // // { // var use = t; // if (x is T t) {} // } // // (2) The pattern variable may not be used outside of the new scope which // is determined by the parent statement. // // { // if (x is T t) {} // } // // var use = t; // // (3) The pattern variable may not be used before assignment in opposite // branches, if any. // // { // if (x is T t) {} // var use = t; // } // // We walk up the tree from the point of null-check and see if any of the above is violated. private bool CanSafelyConvertToPatternMatching() { // Keep track of whether the pattern variable is definitely assigned when false/true. // We start by the null-check itself, if it's compared with '==', the pattern variable // will be definitely assigned when false, because we wrap the is-operator in a !-operator. var defAssignedWhenTrue = _comparison.IsKind(SyntaxKind.NotEqualsExpression, SyntaxKind.IsExpression); foreach (var current in _comparison.Ancestors()) { // Checking for any conditional statement or expression that could possibly // affect or determine the state of definite-assignment of the pattern variable. switch (current.Kind()) { case SyntaxKind.LogicalAndExpression when !defAssignedWhenTrue: case SyntaxKind.LogicalOrExpression when defAssignedWhenTrue: // Since the pattern variable is only definitely assigned if the pattern // succeeded, in the following cases it would not be safe to use pattern-matching. // For example: // // if ((x = o as string) == null && SomeExpression) // if ((x = o as string) != null || SomeExpression) // // Here, x would never be definitely assigned if pattern-matching were used. return false; case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: // Parentheses and cast expressions do not contribute to the flow analysis. case SyntaxKind.ParenthesizedExpression: case SyntaxKind.CastExpression: // Skip over declaration parts to get to the parenting statement // which might be a for-statement or a local declaration statement. case SyntaxKind.EqualsValueClause: case SyntaxKind.VariableDeclarator: case SyntaxKind.VariableDeclaration: continue; case SyntaxKind.LogicalNotExpression: // The !-operator negates the definitive assignment state. defAssignedWhenTrue = !defAssignedWhenTrue; continue; case SyntaxKind.ConditionalExpression: var conditionalExpression = (ConditionalExpressionSyntax)current; if (LocalFlowsIn(defAssignedWhenTrue ? conditionalExpression.WhenFalse : conditionalExpression.WhenTrue)) { // In a conditional expression, the pattern variable // would not be definitely assigned in the opposite branch. return false; } return CheckExpression(conditionalExpression); case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)current; if (!forStatement.Condition.Span.Contains(_comparison.Span)) { // In a for-statement, only the condition expression // can make this definitely assigned in the loop body. return false; } return CheckLoop(forStatement, forStatement.Statement, defAssignedWhenTrue); case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)current; return CheckLoop(whileStatement, whileStatement.Statement, defAssignedWhenTrue); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)current; var oppositeStatement = defAssignedWhenTrue ? ifStatement.Else?.Statement : ifStatement.Statement; if (oppositeStatement != null) { var dataFlow = _semanticModel.AnalyzeDataFlow(oppositeStatement); if (dataFlow.DataFlowsIn.Contains(_localSymbol)) { // Access before assignment is not safe in the opposite branch // as the variable is not definitely assgined at this point. // For example: // // if (o is string x) { } // else { Use(x); } // return false; } if (dataFlow.AlwaysAssigned.Contains(_localSymbol)) { // If the variable is always assigned here, we don't need to check // subsequent statements as it's definitely assigned afterwards. // For example: // // if (o is string x) { } // else { x = null; } // return true; } } if (!defAssignedWhenTrue && !_semanticModel.AnalyzeControlFlow(ifStatement.Statement).EndPointIsReachable) { // Access before assignment here is only valid if we have a negative // pattern-matching in an if-statement with an unreachable endpoint. // For example: // // if (!(o is string x)) { // return; // } // // // The 'return' statement above ensures x is definitely assigned here // Console.WriteLine(x); // return true; } return CheckStatement(ifStatement); } switch (current) { case ExpressionSyntax expression: // If we reached here, it means we have a sub-expression that // does not guarantee definite assignment. We should make sure that // the pattern variable is not used outside of the expression boundaries. return CheckExpression(expression); case StatementSyntax statement: // If we reached here, it means that the null-check is appeared in // a statement. In that case, the variable would be actually in the // scope in subsequent statements, but not definitely assigned. // Therefore, we should ensure that there is no use before assignment. return CheckStatement(statement); } // Bail out for error cases and unhandled cases. break; } return false; } private bool CheckLoop(SyntaxNode statement, StatementSyntax body, bool defAssignedWhenTrue) { if (_operand.Kind() == SyntaxKind.IdentifierName) { // We have something like: // // var x = e as T; // while (b != null) { ... } // // It's not necessarily safe to convert this to: // // while (x is T b) { ... } // // That's because in this case, unlike the original code, we're // type-checking in every iteration, so we do not replace a // simple null check with the "is" operator if it's in a loop. return false; } if (!defAssignedWhenTrue && LocalFlowsIn(body)) { // If the local is accessed before assignment // in the loop body, we should make sure that // the variable is definitely assigned by then. return false; } // The scope of the pattern variables for loops // does not leak out of the loop statement. return !IsAccessedOutOfScope(scope: statement); } private bool CheckExpression(ExpressionSyntax exprsesion) { // It wouldn't be safe to read after the pattern variable is // declared inside a sub-expression, because it would not be // definitely assigned after this point. It's possible to allow // use after assignment but it's rather unlikely to happen. return !IsAccessedOutOfScope(scope: exprsesion); } private bool CheckStatement(StatementSyntax statement) { Debug.Assert(statement != null); // This is either an embedded statement or parented by a block. // If we're parented by a block, then that block will be the scope // of the new variable. Otherwise the scope is the statement itself. if (statement.Parent.IsKind(SyntaxKind.Block, out BlockSyntax block)) { // Check if the local is accessed before assignment // in the subsequent statements. If so, this can't // be converted to pattern-matching. if (LocalFlowsIn(firstStatement: statement.GetNextStatement(), lastStatement: block.Statements.Last())) { return false; } return !IsAccessedOutOfScope(scope: block); } else { return !IsAccessedOutOfScope(scope: statement); } } private bool IsAccessedOutOfScope(SyntaxNode scope) { Debug.Assert(scope != null); var localStatementStart = _localStatement.SpanStart; var comparisonSpanStart = _comparison.SpanStart; var variableName = _localSymbol.Name; var scopeSpan = scope.Span; // Iterate over all descendent nodes to find possible out-of-scope references. foreach (var descendentNode in _enclosingBlock.DescendantNodes()) { var descendentNodeSpanStart = descendentNode.SpanStart; if (descendentNodeSpanStart <= localStatementStart) { // We're not interested in nodes that are apeared before // the local declaration statement. It's either an error // or not the local reference we're looking for. continue; } if (descendentNodeSpanStart >= comparisonSpanStart && scopeSpan.Contains(descendentNode.Span)) { // If this is in the scope and after null-check, we don't bother checking the symbol. continue; } if (descendentNode.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName) && identifierName.Identifier.ValueText == variableName && _localSymbol.Equals(_semanticModel.GetSymbolInfo(identifierName, _cancellationToken).Symbol)) { // If we got here, it means we have a local // reference out of scope of the pattern variable. return true; } } // Either no reference were found, or all // references were inside the given scope. return false; } private bool LocalFlowsIn(SyntaxNode statementOrExpression) { if (statementOrExpression == null) { return false; } if (statementOrExpression.ContainsDiagnostics) { return false; } return _semanticModel.AnalyzeDataFlow(statementOrExpression).DataFlowsIn.Contains(_localSymbol); } private bool LocalFlowsIn(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null || lastStatement == null) { return false; } if (firstStatement.ContainsDiagnostics || lastStatement.ContainsDiagnostics) { return false; } return _semanticModel.AnalyzeDataFlow(firstStatement, lastStatement).DataFlowsIn.Contains(_localSymbol); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { internal partial class CSharpAsAndNullCheckDiagnosticAnalyzer { private readonly struct Analyzer { private readonly SemanticModel _semanticModel; private readonly ILocalSymbol _localSymbol; private readonly ExpressionSyntax _comparison; private readonly ExpressionSyntax _operand; private readonly SyntaxNode _localStatement; private readonly SyntaxNode _enclosingBlock; private readonly CancellationToken _cancellationToken; private Analyzer( SemanticModel semanticModel, ILocalSymbol localSymbol, ExpressionSyntax comparison, ExpressionSyntax operand, SyntaxNode localStatement, SyntaxNode enclosingBlock, CancellationToken cancellationToken) { Debug.Assert(semanticModel != null); Debug.Assert(localSymbol != null); Debug.Assert(comparison != null); Debug.Assert(operand != null); Debug.Assert(localStatement.IsKind(SyntaxKind.LocalDeclarationStatement)); Debug.Assert(enclosingBlock.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection)); _semanticModel = semanticModel; _comparison = comparison; _localSymbol = localSymbol; _operand = operand; _localStatement = localStatement; _enclosingBlock = enclosingBlock; _cancellationToken = cancellationToken; } public static bool CanSafelyConvertToPatternMatching( SemanticModel semanticModel, ILocalSymbol localSymbol, ExpressionSyntax comparison, ExpressionSyntax operand, SyntaxNode localStatement, SyntaxNode enclosingBlock, CancellationToken cancellationToken) { var analyzer = new Analyzer(semanticModel, localSymbol, comparison, operand, localStatement, enclosingBlock, cancellationToken); return analyzer.CanSafelyConvertToPatternMatching(); } // To convert a null-check to pattern-matching, we should make sure of a few things: // // (1) The pattern variable may not be used before the point of declaration. // // { // var use = t; // if (x is T t) {} // } // // (2) The pattern variable may not be used outside of the new scope which // is determined by the parent statement. // // { // if (x is T t) {} // } // // var use = t; // // (3) The pattern variable may not be used before assignment in opposite // branches, if any. // // { // if (x is T t) {} // var use = t; // } // // We walk up the tree from the point of null-check and see if any of the above is violated. private bool CanSafelyConvertToPatternMatching() { // Keep track of whether the pattern variable is definitely assigned when false/true. // We start by the null-check itself, if it's compared with '==', the pattern variable // will be definitely assigned when false, because we wrap the is-operator in a !-operator. var defAssignedWhenTrue = _comparison.IsKind(SyntaxKind.NotEqualsExpression, SyntaxKind.IsExpression); foreach (var current in _comparison.Ancestors()) { // Checking for any conditional statement or expression that could possibly // affect or determine the state of definite-assignment of the pattern variable. switch (current.Kind()) { case SyntaxKind.LogicalAndExpression when !defAssignedWhenTrue: case SyntaxKind.LogicalOrExpression when defAssignedWhenTrue: // Since the pattern variable is only definitely assigned if the pattern // succeeded, in the following cases it would not be safe to use pattern-matching. // For example: // // if ((x = o as string) == null && SomeExpression) // if ((x = o as string) != null || SomeExpression) // // Here, x would never be definitely assigned if pattern-matching were used. return false; case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: // Parentheses and cast expressions do not contribute to the flow analysis. case SyntaxKind.ParenthesizedExpression: case SyntaxKind.CastExpression: // Skip over declaration parts to get to the parenting statement // which might be a for-statement or a local declaration statement. case SyntaxKind.EqualsValueClause: case SyntaxKind.VariableDeclarator: case SyntaxKind.VariableDeclaration: continue; case SyntaxKind.LogicalNotExpression: // The !-operator negates the definitive assignment state. defAssignedWhenTrue = !defAssignedWhenTrue; continue; case SyntaxKind.ConditionalExpression: var conditionalExpression = (ConditionalExpressionSyntax)current; if (LocalFlowsIn(defAssignedWhenTrue ? conditionalExpression.WhenFalse : conditionalExpression.WhenTrue)) { // In a conditional expression, the pattern variable // would not be definitely assigned in the opposite branch. return false; } return CheckExpression(conditionalExpression); case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)current; if (!forStatement.Condition.Span.Contains(_comparison.Span)) { // In a for-statement, only the condition expression // can make this definitely assigned in the loop body. return false; } return CheckLoop(forStatement, forStatement.Statement, defAssignedWhenTrue); case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)current; return CheckLoop(whileStatement, whileStatement.Statement, defAssignedWhenTrue); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)current; var oppositeStatement = defAssignedWhenTrue ? ifStatement.Else?.Statement : ifStatement.Statement; if (oppositeStatement != null) { var dataFlow = _semanticModel.AnalyzeDataFlow(oppositeStatement); if (dataFlow.DataFlowsIn.Contains(_localSymbol)) { // Access before assignment is not safe in the opposite branch // as the variable is not definitely assgined at this point. // For example: // // if (o is string x) { } // else { Use(x); } // return false; } if (dataFlow.AlwaysAssigned.Contains(_localSymbol)) { // If the variable is always assigned here, we don't need to check // subsequent statements as it's definitely assigned afterwards. // For example: // // if (o is string x) { } // else { x = null; } // return true; } } if (!defAssignedWhenTrue && !_semanticModel.AnalyzeControlFlow(ifStatement.Statement).EndPointIsReachable) { // Access before assignment here is only valid if we have a negative // pattern-matching in an if-statement with an unreachable endpoint. // For example: // // if (!(o is string x)) { // return; // } // // // The 'return' statement above ensures x is definitely assigned here // Console.WriteLine(x); // return true; } return CheckStatement(ifStatement); } switch (current) { case ExpressionSyntax expression: // If we reached here, it means we have a sub-expression that // does not guarantee definite assignment. We should make sure that // the pattern variable is not used outside of the expression boundaries. return CheckExpression(expression); case StatementSyntax statement: // If we reached here, it means that the null-check is appeared in // a statement. In that case, the variable would be actually in the // scope in subsequent statements, but not definitely assigned. // Therefore, we should ensure that there is no use before assignment. return CheckStatement(statement); } // Bail out for error cases and unhandled cases. break; } return false; } private bool CheckLoop(SyntaxNode statement, StatementSyntax body, bool defAssignedWhenTrue) { if (_operand.Kind() == SyntaxKind.IdentifierName) { // We have something like: // // var x = e as T; // while (b != null) { ... } // // It's not necessarily safe to convert this to: // // while (x is T b) { ... } // // That's because in this case, unlike the original code, we're // type-checking in every iteration, so we do not replace a // simple null check with the "is" operator if it's in a loop. return false; } if (!defAssignedWhenTrue && LocalFlowsIn(body)) { // If the local is accessed before assignment // in the loop body, we should make sure that // the variable is definitely assigned by then. return false; } // The scope of the pattern variables for loops // does not leak out of the loop statement. return !IsAccessedOutOfScope(scope: statement); } private bool CheckExpression(ExpressionSyntax exprsesion) { // It wouldn't be safe to read after the pattern variable is // declared inside a sub-expression, because it would not be // definitely assigned after this point. It's possible to allow // use after assignment but it's rather unlikely to happen. return !IsAccessedOutOfScope(scope: exprsesion); } private bool CheckStatement(StatementSyntax statement) { Debug.Assert(statement != null); // This is either an embedded statement or parented by a block. // If we're parented by a block, then that block will be the scope // of the new variable. Otherwise the scope is the statement itself. if (statement.Parent.IsKind(SyntaxKind.Block, out BlockSyntax block)) { // Check if the local is accessed before assignment // in the subsequent statements. If so, this can't // be converted to pattern-matching. if (LocalFlowsIn(firstStatement: statement.GetNextStatement(), lastStatement: block.Statements.Last())) { return false; } return !IsAccessedOutOfScope(scope: block); } else { return !IsAccessedOutOfScope(scope: statement); } } private bool IsAccessedOutOfScope(SyntaxNode scope) { Debug.Assert(scope != null); var localStatementStart = _localStatement.SpanStart; var comparisonSpanStart = _comparison.SpanStart; var variableName = _localSymbol.Name; var scopeSpan = scope.Span; // Iterate over all descendent nodes to find possible out-of-scope references. foreach (var descendentNode in _enclosingBlock.DescendantNodes()) { var descendentNodeSpanStart = descendentNode.SpanStart; if (descendentNodeSpanStart <= localStatementStart) { // We're not interested in nodes that are apeared before // the local declaration statement. It's either an error // or not the local reference we're looking for. continue; } if (descendentNodeSpanStart >= comparisonSpanStart && scopeSpan.Contains(descendentNode.Span)) { // If this is in the scope and after null-check, we don't bother checking the symbol. continue; } if (descendentNode.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName) && identifierName.Identifier.ValueText == variableName && _localSymbol.Equals(_semanticModel.GetSymbolInfo(identifierName, _cancellationToken).Symbol)) { // If we got here, it means we have a local // reference out of scope of the pattern variable. return true; } } // Either no reference were found, or all // references were inside the given scope. return false; } private bool LocalFlowsIn(SyntaxNode statementOrExpression) { if (statementOrExpression == null) { return false; } if (statementOrExpression.ContainsDiagnostics) { return false; } return _semanticModel.AnalyzeDataFlow(statementOrExpression).DataFlowsIn.Contains(_localSymbol); } private bool LocalFlowsIn(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null || lastStatement == null) { return false; } if (firstStatement.ContainsDiagnostics || lastStatement.ContainsDiagnostics) { return false; } return _semanticModel.AnalyzeDataFlow(firstStatement, lastStatement).DataFlowsIn.Contains(_localSymbol); } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/Syntax/Parser/XmlDocComments.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseXmlDocComments Inherits BasicTestBase <Fact()> Public Sub ParseOneLineText() ParseAndVerify(<![CDATA[ ''' hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocText() ParseAndVerify(<![CDATA['''hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocElement() ParseAndVerify(<![CDATA['''<qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocComment() ParseAndVerify(<![CDATA['''<!-- qqqqq --> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultilineXmlDocElement() ParseAndVerify(<![CDATA[ ''' '''<qqq> '''<aaa>blah '''</aaa> '''</qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultiLineText() Dim multiline = ParseAndVerify(<![CDATA[ ''' hello doc comments! ''' hello doc comments! Module m1 End Module ]]>).GetRoot() Dim comments = multiline.GetFirstToken.LeadingTrivia Assert.Equal(4, comments.Count) Dim struct = DirectCast(comments(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.DoesNotContain(vbCr, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.DoesNotContain(vbLf, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.Equal(" hello doc comments! hello doc comments!", struct.GetInteriorXml) End Sub <Fact> Public Sub ParseOneLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ", txt) End Sub <Fact()> Public Sub ParseTwoLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim docComment1 = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.Same(docComment, docComment1) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> " & " hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>", txt) End Sub <Fact> Public Sub XmlDocCommentsSpanLines() ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq '''--> <qqq> blah </qqq> ''' hello doc comments! <!-- ''' qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub XmlDocCommentsAttrSpanLines() ParseAndVerify(<![CDATA[ ''' <qqq a '''= ''' '''" '''h ''' &lt; ''' " '''> blah </qqq> Module m1 End Module ]]>) End Sub <WorkItem(893656, "DevDiv/Personal")> <WorkItem(923711, "DevDiv/Personal")> <Fact> Public Sub TickTickTickKind() ParseAndVerify( " '''<qqq> blah </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlElementStartTag).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & "'''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & " '''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & "'''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & " '''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <WorkItem(900384, "DevDiv/Personal")> <Fact> Public Sub InvalidCastExceptionWithEvent() ParseAndVerify(<![CDATA[Class Goo ''' <summary> ''' Goo ''' </summary> Custom Event eventName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class ]]>) End Sub <WorkItem(904414, "DevDiv/Personal")> <Fact> Public Sub ParseMalformedDocComments() ParseAndVerify(<![CDATA[ Module M1 '''<doc> ''' <></> ''' </> '''</doc> '''</root> Sub Main() End Sub End Module Module M2 '''</root> '''<!--* Missing start tag and no content --> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(904903, "DevDiv/Personal")> <Fact> Public Sub ParseShortEndTag() ParseAndVerify(<![CDATA[ '''<qqq> '''<a><b></></> '''</> Module m1 End Module ]]>) End Sub <WorkItem(927580, "DevDiv/Personal")> <WorkItem(927696, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocBadNamespacePrefix() ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>) ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927781, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedEndTag() ParseAndVerify(<![CDATA[Module M1 '''<test> '''</test Sub Main() End Sub '''<doc></doc/> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927785, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedPI() ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, <errors> <error id="30622"/> </errors>) ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="30622"/> </errors>) End Sub <WorkItem(929146, "DevDiv/Personal")> <WorkItem(929147, "DevDiv/Personal")> <WorkItem(929684, "DevDiv/Personal")> <Fact> Public Sub ParseDTDInXmlDoc() ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>) ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(930282, "DevDiv/Personal")> <Fact> Public Sub ParseIncorrectCharactersInDocComment() '!!!!!!!!!!!!!! BELOW TEXT CONTAINS INVISIBLE UNICODE CHARACTERS !!!!!!!!!!!!!! ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>") ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>", VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub Bug16663() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' < 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' </> 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' <?p 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub ParseXmlNameWithLeadingSpaces() ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <WorkItem(547297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547297")> <Fact> Public Sub ParseOpenBracket() ParseAndVerify(<![CDATA[ ''' < Module M End Module ]]>) End Sub <WorkItem(697115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697115")> <Fact()> Public Sub Bug697115() ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.None), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <WorkItem(697269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697269")> <Fact()> Public Sub Bug697269() ParseAndVerify(<![CDATA[ '''<?a Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<?a '''b c<x/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<x><? Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> </errors>) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestDocumentationComment() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class.\r\n" & "''' </summary>\r\n" & "''' <threadsafety static=""true"" instance=""false""/>\r\n" & "''' <preliminary/>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlThreadSafetyElement(), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPreliminaryElement()) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSummaryElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSeeElementAndXmlSeeAlsoElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class and the <seealso cref=""TypeName2""/> class.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class and the "), SyntaxFactory.XmlSeeAlsoElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName2"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlNewLineElement() Dim expected = "''' <summary>\r\n" & "''' This is a summary.\r\n" & "''' </summary>\r\n" & "''' \r\n" & "''' \r\n" & "''' <remarks>\r\n" & "''' \r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This is a summary."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlParamAndParamRefElement() Dim expected = "''' <summary>\r\n" & "''' <paramref name=""b""/>\r\n" & "''' </summary>\r\n" & "''' <param name=""a""></param>\r\n" & "''' <param name=""b""></param>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamRefElement("b"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("a"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("b")) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlReturnsElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <returns>\r\n" & "''' Returns a value.\r\n" & "''' </returns>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlReturnsElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Returns a value."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlRemarksElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <remarks>\r\n" & "''' Same as in class <see cref=""TypeName""/>.\r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Same as in class "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText("."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlExceptionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <exception cref=""InvalidOperationException"">This exception will be thrown if the object is in an invalid state when calling this method.</exception>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlExceptionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("InvalidOperationException")), SyntaxFactory.XmlText("This exception will be thrown if the object is in an invalid state when calling this method."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlPermissionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <permission cref=""MyPermission"">Needs MyPermission to execute.</permission>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPermissionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("MyPermission")), SyntaxFactory.XmlText("Needs MyPermission to execute."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseXmlDocComments Inherits BasicTestBase <Fact()> Public Sub ParseOneLineText() ParseAndVerify(<![CDATA[ ''' hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocText() ParseAndVerify(<![CDATA['''hello doc comments! Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocElement() ParseAndVerify(<![CDATA['''<qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseImmediateXmlDocComment() ParseAndVerify(<![CDATA['''<!-- qqqqq --> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultilineXmlDocElement() ParseAndVerify(<![CDATA[ ''' '''<qqq> '''<aaa>blah '''</aaa> '''</qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub ParseMultiLineText() Dim multiline = ParseAndVerify(<![CDATA[ ''' hello doc comments! ''' hello doc comments! Module m1 End Module ]]>).GetRoot() Dim comments = multiline.GetFirstToken.LeadingTrivia Assert.Equal(4, comments.Count) Dim struct = DirectCast(comments(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.DoesNotContain(vbCr, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.DoesNotContain(vbLf, struct.GetInteriorXml(), StringComparison.Ordinal) Assert.Equal(" hello doc comments! hello doc comments!", struct.GetInteriorXml) End Sub <Fact> Public Sub ParseOneLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ", txt) End Sub <Fact()> Public Sub ParseTwoLineTextAndMarkup() Dim node = ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> ''' hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) Dim tk = node.GetRoot().FindToken(25) Dim docComment = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Dim docComment1 = DirectCast(tk.LeadingTrivia(2).GetStructure, DocumentationCommentTriviaSyntax) Assert.Same(docComment, docComment1) Dim txt = docComment.GetInteriorXml Assert.Equal(" hello doc comments! <!-- qqqqq --> <qqq> blah </qqq> " & " hello doc comments! <!-- qqqqq --> <qqq> blah </qqq>", txt) End Sub <Fact> Public Sub XmlDocCommentsSpanLines() ParseAndVerify(<![CDATA[ ''' hello doc comments! <!-- qqqqq '''--> <qqq> blah </qqq> ''' hello doc comments! <!-- ''' qqqqq --> <qqq> blah </qqq> Module m1 End Module ]]>) End Sub <Fact> Public Sub XmlDocCommentsAttrSpanLines() ParseAndVerify(<![CDATA[ ''' <qqq a '''= ''' '''" '''h ''' &lt; ''' " '''> blah </qqq> Module m1 End Module ]]>) End Sub <WorkItem(893656, "DevDiv/Personal")> <WorkItem(923711, "DevDiv/Personal")> <Fact> Public Sub TickTickTickKind() ParseAndVerify( " '''<qqq> blah </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlElementStartTag).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & "'''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceString() ParseAndVerify( "'''<qqq aa=""qq" & vbCrLf & " '''qqqqqqqqqqqqqqqqqq""> </qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlTextLiteralToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & "'''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <Fact> Public Sub TickTickTickSpaceMarkup() ParseAndVerify( "'''<qqq " & vbCrLf & " '''aaaaaaaaaaaaaaa=""qq""> " & vbCrLf & "'''</qqq>" & vbCrLf & "Module m1" & vbCrLf & "End Module" ). FindNodeOrTokenByKind(SyntaxKind.XmlNameToken, 2).VerifyPrecedingCommentIsTrivia() End Sub <WorkItem(900384, "DevDiv/Personal")> <Fact> Public Sub InvalidCastExceptionWithEvent() ParseAndVerify(<![CDATA[Class Goo ''' <summary> ''' Goo ''' </summary> Custom Event eventName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class ]]>) End Sub <WorkItem(904414, "DevDiv/Personal")> <Fact> Public Sub ParseMalformedDocComments() ParseAndVerify(<![CDATA[ Module M1 '''<doc> ''' <></> ''' </> '''</doc> '''</root> Sub Main() End Sub End Module Module M2 '''</root> '''<!--* Missing start tag and no content --> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(904903, "DevDiv/Personal")> <Fact> Public Sub ParseShortEndTag() ParseAndVerify(<![CDATA[ '''<qqq> '''<a><b></></> '''</> Module m1 End Module ]]>) End Sub <WorkItem(927580, "DevDiv/Personal")> <WorkItem(927696, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocBadNamespacePrefix() ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>) ParseAndVerify(<![CDATA[Module M1 '''<doc xmlns:a:b="abc"/> Sub Main() End Sub End Module]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927781, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedEndTag() ParseAndVerify(<![CDATA[Module M1 '''<test> '''</test Sub Main() End Sub '''<doc></doc/> Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(927785, "DevDiv/Personal")> <Fact> Public Sub ParseXmlDocCommentMalformedPI() ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, <errors> <error id="30622"/> </errors>) ParseAndVerify(<![CDATA[Module M1 '''<doc><? ?></doc> Sub Main() End Sub End Module '''<?pi Sub Goo() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="30622"/> </errors>) End Sub <WorkItem(929146, "DevDiv/Personal")> <WorkItem(929147, "DevDiv/Personal")> <WorkItem(929684, "DevDiv/Personal")> <Fact> Public Sub ParseDTDInXmlDoc() ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>) ParseAndVerify(<![CDATA[Module Module1 '''<!DOCTYPE Goo []> '''<summary> '''</summary> Sub Main() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(930282, "DevDiv/Personal")> <Fact> Public Sub ParseIncorrectCharactersInDocComment() '!!!!!!!!!!!!!! BELOW TEXT CONTAINS INVISIBLE UNICODE CHARACTERS !!!!!!!!!!!!!! ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>") ParseAndVerify("'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>" & vbCrLf & "'''<doc/>", VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub Bug16663() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' < 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' </> 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="c.vb"><![CDATA[ Module M Sub M() GoTo 1 ''' <?p 1: End Sub End Module ]]></file> </compilation>) compilation.AssertNoErrors() End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <Fact()> Public Sub ParseXmlNameWithLeadingSpaces() ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> </errors>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>) ParseAndVerify(<![CDATA[ ''' < ''' summary/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304" warning="True"/> <error id="42304" warning="True"/> <error id="42304" warning="True"/> </errors>) End Sub <WorkItem(530663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530663")> <WorkItem(547297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547297")> <Fact> Public Sub ParseOpenBracket() ParseAndVerify(<![CDATA[ ''' < Module M End Module ]]>) End Sub <WorkItem(697115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697115")> <Fact()> Public Sub Bug697115() ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.None), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) ParseAndVerify(<![CDATA[ Module M Dim x = <x><%= Function() ''' <summary/> Sub M() End Sub End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Parse), <errors> <error id="30625"/> <error id="31151"/> <error id="36674"/> <error id="31159"/> <error id="31165"/> <error id="30636"/> </errors>) End Sub <WorkItem(697269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697269")> <Fact()> Public Sub Bug697269() ParseAndVerify(<![CDATA[ '''<?a Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<?a '''b c<x/> Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> </errors>) ParseAndVerify(<![CDATA[ '''<x><? Module M End Module ]]>, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose), <errors> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> <error id="42304"/> </errors>) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestDocumentationComment() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class.\r\n" & "''' </summary>\r\n" & "''' <threadsafety static=""true"" instance=""false""/>\r\n" & "''' <preliminary/>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlThreadSafetyElement(), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPreliminaryElement()) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSummaryElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlSeeElementAndXmlSeeAlsoElement() Dim expected = "''' <summary>\r\n" & "''' This class provides extension methods for the <see cref=""TypeName""/> class and the <seealso cref=""TypeName2""/> class.\r\n" & "''' </summary>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This class provides extension methods for the "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText(" class and the "), SyntaxFactory.XmlSeeAlsoElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName2"))), SyntaxFactory.XmlText(" class."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlNewLineElement() Dim expected = "''' <summary>\r\n" & "''' This is a summary.\r\n" & "''' </summary>\r\n" & "''' \r\n" & "''' \r\n" & "''' <remarks>\r\n" & "''' \r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("This is a summary."), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlParamAndParamRefElement() Dim expected = "''' <summary>\r\n" & "''' <paramref name=""b""/>\r\n" & "''' </summary>\r\n" & "''' <param name=""a""></param>\r\n" & "''' <param name=""b""></param>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamRefElement("b"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("a"), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlParamElement("b")) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlReturnsElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <returns>\r\n" & "''' Returns a value.\r\n" & "''' </returns>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlReturnsElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Returns a value."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlRemarksElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <remarks>\r\n" & "''' Same as in class <see cref=""TypeName""/>.\r\n" & "''' </remarks>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlRemarksElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlText("Same as in class "), SyntaxFactory.XmlSeeElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("TypeName"))), SyntaxFactory.XmlText("."), SyntaxFactory.XmlNewLine("\r\n"))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlExceptionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <exception cref=""InvalidOperationException"">This exception will be thrown if the object is in an invalid state when calling this method.</exception>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlExceptionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("InvalidOperationException")), SyntaxFactory.XmlText("This exception will be thrown if the object is in an invalid state when calling this method."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub <Fact> <Trait("Feature", "Xml Documentation Comments")> Public Sub TestXmlPermissionElement() Dim expected = "''' <summary>\r\n" & "''' \r\n" & "''' </summary>\r\n" & "''' <permission cref=""MyPermission"">Needs MyPermission to execute.</permission>" Dim documentationComment As DocumentationCommentTriviaSyntax = SyntaxFactory.DocumentationComment( SyntaxFactory.XmlSummaryElement( SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlNewLine("\r\n")), SyntaxFactory.XmlNewLine("\r\n"), SyntaxFactory.XmlPermissionElement( SyntaxFactory.CrefReference( SyntaxFactory.ParseTypeName("MyPermission")), SyntaxFactory.XmlText("Needs MyPermission to execute."))) Dim actual = documentationComment.ToFullString() Assert.Equal(Of String)(expected, actual) End Sub End Class
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/CodeAnalysisTest/Collections/List/IEnumerable.NonGeneric.Tests.cs
// Licensed to the .NET Foundation under one or more 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/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IEnumerable.NonGeneric.Tests.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.Collections; using System.Collections.Generic; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of any class that implements the nongeneric /// IEnumerable interface /// </summary> public abstract partial class IEnumerable_NonGeneric_Tests : TestBase { #region IEnumerable Helper Methods /// <summary> /// Creates an instance of an IEnumerable that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned IEnumerable contains.</param> /// <returns>An instance of an IEnumerable that can be used for testing.</returns> protected abstract IEnumerable NonGenericIEnumerableFactory(int count); /// <summary> /// Modifies the given IEnumerable such that any enumerators for that IEnumerable will be /// invalidated. /// </summary> /// <param name="enumerable">An IEnumerable to modify</param> /// <returns>true if the enumerable was successfully modified. Else false.</returns> protected delegate bool ModifyEnumerable(IEnumerable enumerable); /// <summary> /// To be implemented in the concrete collections test classes. Returns a set of ModifyEnumerable delegates /// that modify the enumerable passed to them. /// </summary> protected abstract IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations); protected virtual ModifyOperation ModifyEnumeratorThrows => ModifyOperation.Add | ModifyOperation.Insert | ModifyOperation.Overwrite | ModifyOperation.Remove | ModifyOperation.Clear; protected virtual ModifyOperation ModifyEnumeratorAllowed => ModifyOperation.None; /// <summary> /// The Reset method is provided for COM interoperability. It does not necessarily need to be /// implemented; instead, the implementer can simply throw a NotSupportedException. /// /// If Reset is not implemented, this property must return False. The default value is true. /// </summary> protected virtual bool ResetImplemented => true; /// <summary> /// When calling Current of the enumerator before the first MoveNext, after the end of the collection, /// or after modification of the enumeration, the resulting behavior is undefined. Tests are included /// to cover two behavioral scenarios: /// - Throwing an InvalidOperationException /// - Returning an undefined value. /// /// If this property is set to true, the tests ensure that the exception is thrown. The default value is /// false. /// </summary> protected virtual bool Enumerator_Current_UndefinedOperation_Throws => false; /// <summary> /// Whether the collection can be serialized. /// </summary> protected virtual bool SupportsSerialization => true; /// <summary> /// Specifies whether this IEnumerable follows some sort of ordering pattern. /// </summary> protected virtual EnumerableOrder Order => EnumerableOrder.Sequential; /// <summary> /// An enum to allow specification of the order of the Enumerable. Used in validation for enumerables. /// </summary> protected enum EnumerableOrder { Unspecified, Sequential } #endregion #region GetEnumerator() [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_GetEnumerator_NoExceptionsWhileGetting(int count) { IEnumerable enumerable = NonGenericIEnumerableFactory(count); Assert.NotNull(enumerable.GetEnumerator()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_GetEnumerator_ReturnsUniqueEnumerator(int count) { //Tests that the enumerators returned by GetEnumerator operate independently of one another IEnumerable enumerable = NonGenericIEnumerableFactory(count); int iterations = 0; foreach (object item in enumerable) foreach (object item2 in enumerable) foreach (object item3 in enumerable) iterations++; Assert.Equal(count * count * count, iterations); } #endregion #region Enumerator.MoveNext [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_FromStartToFinish(int count) { int iterations = 0; IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); while (enumerator.MoveNext()) iterations++; Assert.Equal(count, iterations); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_AfterEndOfCollection(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); for (int i = 0; i < count; i++) enumerator.MoveNext(); Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } #endregion #region Enumerator.Current [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_FromStartToFinish(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); object current; while (enumerator.MoveNext()) current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_ReturnsSameValueOnRepeatedCalls(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); while (enumerator.MoveNext()) { object current = enumerator.Current; Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_ReturnsSameObjectsOnDifferentEnumerators(int count) { // Ensures that the elements returned from enumeration are exactly the same collection of // elements returned from a previous enumeration IEnumerable enumerable = NonGenericIEnumerableFactory(count); Dictionary<object, int> firstValues = new Dictionary<object, int>(count); Dictionary<object, int> secondValues = new Dictionary<object, int>(count); foreach (object item in enumerable) firstValues[item] = firstValues.ContainsKey(item) ? firstValues[item]++ : 1; foreach (object item in enumerable) secondValues[item] = secondValues.ContainsKey(item) ? secondValues[item]++ : 1; Assert.Equal(firstValues.Count, secondValues.Count); foreach (object key in firstValues.Keys) Assert.Equal(firstValues[key], secondValues[key]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_BeforeFirstMoveNext_UndefinedBehavior(int count) { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_AfterEndOfEnumerable_UndefinedBehavior(int count) { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_ModifiedDuringEnumeration_UndefinedBehavior(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) { if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } }); } #endregion #region Enumerator.Reset [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_BeforeIteration_Support(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); if (ResetImplemented) enumerator.Reset(); else Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IEnumerable.NonGeneric.Tests.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.Collections; using System.Collections.Generic; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of any class that implements the nongeneric /// IEnumerable interface /// </summary> public abstract partial class IEnumerable_NonGeneric_Tests : TestBase { #region IEnumerable Helper Methods /// <summary> /// Creates an instance of an IEnumerable that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned IEnumerable contains.</param> /// <returns>An instance of an IEnumerable that can be used for testing.</returns> protected abstract IEnumerable NonGenericIEnumerableFactory(int count); /// <summary> /// Modifies the given IEnumerable such that any enumerators for that IEnumerable will be /// invalidated. /// </summary> /// <param name="enumerable">An IEnumerable to modify</param> /// <returns>true if the enumerable was successfully modified. Else false.</returns> protected delegate bool ModifyEnumerable(IEnumerable enumerable); /// <summary> /// To be implemented in the concrete collections test classes. Returns a set of ModifyEnumerable delegates /// that modify the enumerable passed to them. /// </summary> protected abstract IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations); protected virtual ModifyOperation ModifyEnumeratorThrows => ModifyOperation.Add | ModifyOperation.Insert | ModifyOperation.Overwrite | ModifyOperation.Remove | ModifyOperation.Clear; protected virtual ModifyOperation ModifyEnumeratorAllowed => ModifyOperation.None; /// <summary> /// The Reset method is provided for COM interoperability. It does not necessarily need to be /// implemented; instead, the implementer can simply throw a NotSupportedException. /// /// If Reset is not implemented, this property must return False. The default value is true. /// </summary> protected virtual bool ResetImplemented => true; /// <summary> /// When calling Current of the enumerator before the first MoveNext, after the end of the collection, /// or after modification of the enumeration, the resulting behavior is undefined. Tests are included /// to cover two behavioral scenarios: /// - Throwing an InvalidOperationException /// - Returning an undefined value. /// /// If this property is set to true, the tests ensure that the exception is thrown. The default value is /// false. /// </summary> protected virtual bool Enumerator_Current_UndefinedOperation_Throws => false; /// <summary> /// Whether the collection can be serialized. /// </summary> protected virtual bool SupportsSerialization => true; /// <summary> /// Specifies whether this IEnumerable follows some sort of ordering pattern. /// </summary> protected virtual EnumerableOrder Order => EnumerableOrder.Sequential; /// <summary> /// An enum to allow specification of the order of the Enumerable. Used in validation for enumerables. /// </summary> protected enum EnumerableOrder { Unspecified, Sequential } #endregion #region GetEnumerator() [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_GetEnumerator_NoExceptionsWhileGetting(int count) { IEnumerable enumerable = NonGenericIEnumerableFactory(count); Assert.NotNull(enumerable.GetEnumerator()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_GetEnumerator_ReturnsUniqueEnumerator(int count) { //Tests that the enumerators returned by GetEnumerator operate independently of one another IEnumerable enumerable = NonGenericIEnumerableFactory(count); int iterations = 0; foreach (object item in enumerable) foreach (object item2 in enumerable) foreach (object item3 in enumerable) iterations++; Assert.Equal(count * count * count, iterations); } #endregion #region Enumerator.MoveNext [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_FromStartToFinish(int count) { int iterations = 0; IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); while (enumerator.MoveNext()) iterations++; Assert.Equal(count, iterations); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_AfterEndOfCollection(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); for (int i = 0; i < count; i++) enumerator.MoveNext(); Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); }); } #endregion #region Enumerator.Current [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_FromStartToFinish(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); object current; while (enumerator.MoveNext()) current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_ReturnsSameValueOnRepeatedCalls(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); while (enumerator.MoveNext()) { object current = enumerator.Current; Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Current_ReturnsSameObjectsOnDifferentEnumerators(int count) { // Ensures that the elements returned from enumeration are exactly the same collection of // elements returned from a previous enumeration IEnumerable enumerable = NonGenericIEnumerableFactory(count); Dictionary<object, int> firstValues = new Dictionary<object, int>(count); Dictionary<object, int> secondValues = new Dictionary<object, int>(count); foreach (object item in enumerable) firstValues[item] = firstValues.ContainsKey(item) ? firstValues[item]++ : 1; foreach (object item in enumerable) secondValues[item] = secondValues.ContainsKey(item) ? secondValues[item]++ : 1; Assert.Equal(firstValues.Count, secondValues.Count); foreach (object key in firstValues.Keys) Assert.Equal(firstValues[key], secondValues[key]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_BeforeFirstMoveNext_UndefinedBehavior(int count) { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_AfterEndOfEnumerable_UndefinedBehavior(int count) { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_Current_ModifiedDuringEnumeration_UndefinedBehavior(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { object current; IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) { if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } }); } #endregion #region Enumerator.Reset [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_BeforeIteration_Support(int count) { IEnumerator enumerator = NonGenericIEnumerableFactory(count).GetEnumerator(); if (ResetImplemented) enumerator.Reset(); else Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_NonGeneric_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable enumerable = NonGenericIEnumerableFactory(count); IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); }); } #endregion } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Scripting/CSharpTest.Desktop/ObjectFormatterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void DebuggerProxy_FrameworkTypes_ArrayList() { var obj = new ArrayList { 1, 2, true, "goo" }; var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ArrayList(4) { 1, 2, true, \"goo\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Hashtable() { var obj = new Hashtable { { new byte[] { 1, 2 }, new[] { 1,2,3 } }, }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Hashtable(1)", "{ byte[2] { 1, 2 }, int[3] { 1, 2, 3 } }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Queue(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Stack(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { SortedList obj = new SortedList(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); obj = new SortedList(); obj.Add(new[] { 3 }, new int[] { 4 }); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } // TODO: move to portable [Fact] public void VBBackingFields_DebuggerBrowsable() { string source = @" Imports System Class C Public WithEvents WE As C Public Event E As Action Public Property A As Integer End Class "; var compilation = VB.VisualBasicCompilation.Create( "goo", new[] { VB.VisualBasicSyntaxTree.ParseText(source) }, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly) }, new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug)); Assembly a; using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); a = Assembly.Load(stream.ToArray()); } var c = a.GetType("C"); var obj = Activator.CreateInstance(c); var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "C", "A: 0", "WE: null" ); var attrsA = c.GetField("_A", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsWE = c.GetField("_WE", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsE = c.GetField("EEvent", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); Assert.Equal(1, attrsA.Length); Assert.Equal(1, attrsWE.Length); Assert.Equal(1, attrsE.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.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { private static readonly ObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void DebuggerProxy_FrameworkTypes_ArrayList() { var obj = new ArrayList { 1, 2, true, "goo" }; var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ArrayList(4) { 1, 2, true, \"goo\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Hashtable() { var obj = new Hashtable { { new byte[] { 1, 2 }, new[] { 1,2,3 } }, }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Hashtable(1)", "{ byte[2] { 1, 2 }, int[3] { 1, 2, 3 } }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Queue(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Stack(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { SortedList obj = new SortedList(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); obj = new SortedList(); obj.Add(new[] { 3 }, new int[] { 4 }); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } // TODO: move to portable [Fact] public void VBBackingFields_DebuggerBrowsable() { string source = @" Imports System Class C Public WithEvents WE As C Public Event E As Action Public Property A As Integer End Class "; var compilation = VB.VisualBasicCompilation.Create( "goo", new[] { VB.VisualBasicSyntaxTree.ParseText(source) }, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly) }, new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug)); Assembly a; using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); a = Assembly.Load(stream.ToArray()); } var c = a.GetType("C"); var obj = Activator.CreateInstance(c); var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "C", "A: 0", "WE: null" ); var attrsA = c.GetField("_A", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsWE = c.GetField("_WE", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); var attrsE = c.GetField("EEvent", BindingFlags.Instance | BindingFlags.NonPublic).GetCustomAttributes(typeof(DebuggerBrowsableAttribute), true); Assert.Equal(1, attrsA.Length); Assert.Equal(1, attrsWE.Length); Assert.Equal(1, attrsE.Length); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/Symbols/SymbolCompletionState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Text; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct SymbolCompletionState { /// <summary> /// This field keeps track of the <see cref="CompletionPart"/>s for which we already retrieved /// diagnostics. We shouldn't return from ForceComplete (i.e. indicate that diagnostics are /// available) until this is equal to <see cref="CompletionPart.All"/>, except that when completing /// with a given position, we might not complete <see cref="CompletionPart"/>.Member*. /// /// Since completeParts is used as a flag indicating completion of other assignments /// it must be volatile to ensure the read is not reordered/optimized to happen /// before the writes. /// </summary> private volatile int _completeParts; internal int IncompleteParts { get { return ~_completeParts & (int)CompletionPart.All; } } /// <summary> /// Used to force (source) symbols to a given state of completion when the only potential remaining /// part is attributes. This does force the invariant on the caller that the implementation of /// of <see cref="Symbol.GetAttributes"/> will set the part <see cref="CompletionPart.Attributes"/> on /// the thread that actually completes the loading of attributes. Failure to do so will potentially /// result in a deadlock. /// </summary> /// <param name="symbol">The owning source symbol.</param> internal void DefaultForceComplete(Symbol symbol, CancellationToken cancellationToken) { Debug.Assert(symbol.RequiresCompletion); if (!HasComplete(CompletionPart.Attributes)) { _ = symbol.GetAttributes(); // Consider the following items: // 1. It is possible for parallel calls to GetAttributes to exist // 2. GetAttributes implementation can validly return when the attributes are available but before the // CompletionParts.Attributes value is set. // 3. GetAttributes implementation typically have the invariant that the thread which completes the // loading of attributes is the one which sets CompletionParts.Attributes. // 4. This call cannot correctly return until CompletionParts.Attributes is set. // // Note: #2 above is common practice amongst all of the symbols. // // Note: #3 above is an invariant that has existed in the code base for some time. It's not 100% clear // whether this invariant is tied to correctness or not. The most compelling example though is // SourceEventSymbol which raises SymbolDeclaredEvent before CompletionPart.Attributes is noted as completed. // Many other implementations have this pattern but no apparent code which could depend on it. SpinWaitComplete(CompletionPart.Attributes, cancellationToken); } // any other values are completion parts intended for other kinds of symbols NotePartComplete(CompletionPart.All); } internal bool HasComplete(CompletionPart part) { // completeParts is used as a flag indicating completion of other assignments // Volatile.Read is used to ensure the read is not reordered/optimized to happen // before the writes. return (_completeParts & (int)part) == (int)part; } internal bool NotePartComplete(CompletionPart part) { // passing volatile completeParts byref is ok here. // ThreadSafeFlagOperations.Set performs interlocked assignments #pragma warning disable 0420 return ThreadSafeFlagOperations.Set(ref _completeParts, (int)part); #pragma warning restore 0420 } /// <summary> /// Produce the next (i.e. lowest) CompletionPart (bit) that is not set. /// </summary> internal CompletionPart NextIncompletePart { get { // NOTE: It's very important to store this value in a local. // If we were to inline the field access, the value of the // field could change between the two accesses and the formula // might not produce a result with a single 1-bit. int incomplete = IncompleteParts; int next = incomplete & ~(incomplete - 1); Debug.Assert(HasAtMostOneBitSet(next), "ForceComplete won't handle the result correctly if more than one bit is set."); return (CompletionPart)next; } } /// <remarks> /// Since this formula is rather opaque, a demonstration of its correctness is /// provided in Roslyn.Compilers.CSharp.UnitTests.CompletionTests.TestHasAtMostOneBitSet. /// </remarks> internal static bool HasAtMostOneBitSet(int bits) { return (bits & (bits - 1)) == 0; } internal void SpinWaitComplete(CompletionPart part, CancellationToken cancellationToken) { if (HasComplete(part)) { return; } // Don't return until we've seen all of the requested CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). var spinWait = new SpinWait(); while (!HasComplete(part)) { cancellationToken.ThrowIfCancellationRequested(); spinWait.SpinOnce(); } } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("CompletionParts("); bool any = false; for (int i = 0; ; i++) { int bit = (1 << i); if ((bit & (int)CompletionPart.All) == 0) break; if ((bit & _completeParts) != 0) { if (any) result.Append(", "); result.Append(i); any = true; } } result.Append(")"); return result.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Text; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct SymbolCompletionState { /// <summary> /// This field keeps track of the <see cref="CompletionPart"/>s for which we already retrieved /// diagnostics. We shouldn't return from ForceComplete (i.e. indicate that diagnostics are /// available) until this is equal to <see cref="CompletionPart.All"/>, except that when completing /// with a given position, we might not complete <see cref="CompletionPart"/>.Member*. /// /// Since completeParts is used as a flag indicating completion of other assignments /// it must be volatile to ensure the read is not reordered/optimized to happen /// before the writes. /// </summary> private volatile int _completeParts; internal int IncompleteParts { get { return ~_completeParts & (int)CompletionPart.All; } } /// <summary> /// Used to force (source) symbols to a given state of completion when the only potential remaining /// part is attributes. This does force the invariant on the caller that the implementation of /// of <see cref="Symbol.GetAttributes"/> will set the part <see cref="CompletionPart.Attributes"/> on /// the thread that actually completes the loading of attributes. Failure to do so will potentially /// result in a deadlock. /// </summary> /// <param name="symbol">The owning source symbol.</param> internal void DefaultForceComplete(Symbol symbol, CancellationToken cancellationToken) { Debug.Assert(symbol.RequiresCompletion); if (!HasComplete(CompletionPart.Attributes)) { _ = symbol.GetAttributes(); // Consider the following items: // 1. It is possible for parallel calls to GetAttributes to exist // 2. GetAttributes implementation can validly return when the attributes are available but before the // CompletionParts.Attributes value is set. // 3. GetAttributes implementation typically have the invariant that the thread which completes the // loading of attributes is the one which sets CompletionParts.Attributes. // 4. This call cannot correctly return until CompletionParts.Attributes is set. // // Note: #2 above is common practice amongst all of the symbols. // // Note: #3 above is an invariant that has existed in the code base for some time. It's not 100% clear // whether this invariant is tied to correctness or not. The most compelling example though is // SourceEventSymbol which raises SymbolDeclaredEvent before CompletionPart.Attributes is noted as completed. // Many other implementations have this pattern but no apparent code which could depend on it. SpinWaitComplete(CompletionPart.Attributes, cancellationToken); } // any other values are completion parts intended for other kinds of symbols NotePartComplete(CompletionPart.All); } internal bool HasComplete(CompletionPart part) { // completeParts is used as a flag indicating completion of other assignments // Volatile.Read is used to ensure the read is not reordered/optimized to happen // before the writes. return (_completeParts & (int)part) == (int)part; } internal bool NotePartComplete(CompletionPart part) { // passing volatile completeParts byref is ok here. // ThreadSafeFlagOperations.Set performs interlocked assignments #pragma warning disable 0420 return ThreadSafeFlagOperations.Set(ref _completeParts, (int)part); #pragma warning restore 0420 } /// <summary> /// Produce the next (i.e. lowest) CompletionPart (bit) that is not set. /// </summary> internal CompletionPart NextIncompletePart { get { // NOTE: It's very important to store this value in a local. // If we were to inline the field access, the value of the // field could change between the two accesses and the formula // might not produce a result with a single 1-bit. int incomplete = IncompleteParts; int next = incomplete & ~(incomplete - 1); Debug.Assert(HasAtMostOneBitSet(next), "ForceComplete won't handle the result correctly if more than one bit is set."); return (CompletionPart)next; } } /// <remarks> /// Since this formula is rather opaque, a demonstration of its correctness is /// provided in Roslyn.Compilers.CSharp.UnitTests.CompletionTests.TestHasAtMostOneBitSet. /// </remarks> internal static bool HasAtMostOneBitSet(int bits) { return (bits & (bits - 1)) == 0; } internal void SpinWaitComplete(CompletionPart part, CancellationToken cancellationToken) { if (HasComplete(part)) { return; } // Don't return until we've seen all of the requested CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). var spinWait = new SpinWait(); while (!HasComplete(part)) { cancellationToken.ThrowIfCancellationRequested(); spinWait.SpinOnce(); } } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("CompletionParts("); bool any = false; for (int i = 0; ; i++) { int bit = (1 << i); if ((bit & (int)CompletionPart.All) == 0) break; if ((bit & _completeParts) != 0) { if (any) result.Append(", "); result.Append(i); any = true; } } result.Append(")"); return result.ToString(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/Core/Portable/ExtractMethod/SimpleExtractMethodResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExtractMethod { internal class SimpleExtractMethodResult : ExtractMethodResult { public SimpleExtractMethodResult( OperationStatus status, Document document, SyntaxToken invocationNameToken, SyntaxNode methodDefinition) : base(status.Flag, status.Reasons, document, invocationNameToken, methodDefinition) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExtractMethod { internal class SimpleExtractMethodResult : ExtractMethodResult { public SimpleExtractMethodResult( OperationStatus status, Document document, SyntaxToken invocationNameToken, SyntaxNode methodDefinition) : base(status.Flag, status.Reasons, document, invocationNameToken, methodDefinition) { } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxTrivia.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxTrivia : CSharpSyntaxNode { public readonly string Text; internal SyntaxTrivia(SyntaxKind kind, string text, DiagnosticInfo[]? diagnostics = null, SyntaxAnnotation[]? annotations = null) : base(kind, diagnostics, annotations, text.Length) { this.Text = text; if (kind == SyntaxKind.PreprocessingMessageTrivia) { this.flags |= NodeFlags.ContainsSkippedText; } } internal SyntaxTrivia(ObjectReader reader) : base(reader) { this.Text = reader.ReadString(); this.FullWidth = this.Text.Length; } static SyntaxTrivia() { ObjectBinder.RegisterTypeReader(typeof(SyntaxTrivia), r => new SyntaxTrivia(r)); } public override bool IsTrivia => true; internal override bool ShouldReuseInSerialization => this.Kind == SyntaxKind.WhitespaceTrivia && FullWidth < Lexer.MaxCachedTokenSize; internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteString(this.Text); } internal static SyntaxTrivia Create(SyntaxKind kind, string text) { return new SyntaxTrivia(kind, text); } public override string ToFullString() { return this.Text; } public override string ToString() { return this.Text; } internal override GreenNode GetSlot(int index) { throw ExceptionUtilities.Unreachable; } public override int Width { get { Debug.Assert(this.FullWidth == this.Text.Length); return this.FullWidth; } } public override int GetLeadingTriviaWidth() { return 0; } public override int GetTrailingTriviaWidth() { return 0; } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) { return new SyntaxTrivia(this.Kind, this.Text, diagnostics, GetAnnotations()); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new SyntaxTrivia(this.Kind, this.Text, GetDiagnostics(), annotations); } public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) { return visitor.VisitTrivia(this); } public override void Accept(CSharpSyntaxVisitor visitor) { visitor.VisitTrivia(this); } protected override void WriteTriviaTo(System.IO.TextWriter writer) { writer.Write(Text); } public static implicit operator CodeAnalysis.SyntaxTrivia(SyntaxTrivia trivia) { return new CodeAnalysis.SyntaxTrivia(token: default, trivia, position: 0, index: 0); } public override bool IsEquivalentTo(GreenNode? other) { if (!base.IsEquivalentTo(other)) { return false; } if (this.Text != ((SyntaxTrivia)other).Text) { return false; } return true; } internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) { throw ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal class SyntaxTrivia : CSharpSyntaxNode { public readonly string Text; internal SyntaxTrivia(SyntaxKind kind, string text, DiagnosticInfo[]? diagnostics = null, SyntaxAnnotation[]? annotations = null) : base(kind, diagnostics, annotations, text.Length) { this.Text = text; if (kind == SyntaxKind.PreprocessingMessageTrivia) { this.flags |= NodeFlags.ContainsSkippedText; } } internal SyntaxTrivia(ObjectReader reader) : base(reader) { this.Text = reader.ReadString(); this.FullWidth = this.Text.Length; } static SyntaxTrivia() { ObjectBinder.RegisterTypeReader(typeof(SyntaxTrivia), r => new SyntaxTrivia(r)); } public override bool IsTrivia => true; internal override bool ShouldReuseInSerialization => this.Kind == SyntaxKind.WhitespaceTrivia && FullWidth < Lexer.MaxCachedTokenSize; internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteString(this.Text); } internal static SyntaxTrivia Create(SyntaxKind kind, string text) { return new SyntaxTrivia(kind, text); } public override string ToFullString() { return this.Text; } public override string ToString() { return this.Text; } internal override GreenNode GetSlot(int index) { throw ExceptionUtilities.Unreachable; } public override int Width { get { Debug.Assert(this.FullWidth == this.Text.Length); return this.FullWidth; } } public override int GetLeadingTriviaWidth() { return 0; } public override int GetTrailingTriviaWidth() { return 0; } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics) { return new SyntaxTrivia(this.Kind, this.Text, diagnostics, GetAnnotations()); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new SyntaxTrivia(this.Kind, this.Text, GetDiagnostics(), annotations); } public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) { return visitor.VisitTrivia(this); } public override void Accept(CSharpSyntaxVisitor visitor) { visitor.VisitTrivia(this); } protected override void WriteTriviaTo(System.IO.TextWriter writer) { writer.Write(Text); } public static implicit operator CodeAnalysis.SyntaxTrivia(SyntaxTrivia trivia) { return new CodeAnalysis.SyntaxTrivia(token: default, trivia, position: 0, index: 0); } public override bool IsEquivalentTo(GreenNode? other) { if (!base.IsEquivalentTo(other)) { return false; } if (this.Text != ((SyntaxTrivia)other).Text) { return false; } return true; } internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) { throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Portable/Symbols/MetadataOrSourceAssemblySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents source or metadata assembly. ''' </summary> ''' <remarks></remarks> Friend MustInherit Class MetadataOrSourceAssemblySymbol Inherits NonMissingAssemblySymbol ''' <summary> ''' An array of cached Cor types defined in this assembly. ''' Lazily filled by GetSpecialType method. ''' </summary> ''' <remarks></remarks> Private _lazySpecialTypes() As NamedTypeSymbol ''' <summary> ''' How many Cor types have we cached so far. ''' </summary> Private _cachedSpecialTypes As Integer ''' <summary> ''' Lookup declaration for predefined CorLib type in this Assembly. Only should be ''' called if it is know that this is the Cor Library (mscorlib). ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol #If DEBUG Then For Each [module] In Me.Modules Debug.Assert([module].GetReferencedAssemblies().Length = 0) Next #End If If _lazySpecialTypes Is Nothing OrElse _lazySpecialTypes(type) Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim [module] As ModuleSymbol = Me.Modules(0) Dim result As NamedTypeSymbol = [module].LookupTopLevelMetadataType(emittedName) If result.TypeKind <> TypeKind.Error AndAlso result.DeclaredAccessibility <> Accessibility.Public Then result = New MissingMetadataTypeSymbol.TopLevel([module], emittedName, type) End If RegisterDeclaredSpecialType(result) End If Return _lazySpecialTypes(type) End Function ''' <summary> ''' Register declaration of predefined CorLib type in this Assembly. ''' </summary> ''' <param name="corType"></param> Friend Overrides Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol) Dim typeId As SpecialType = corType.SpecialType Debug.Assert(typeId <> SpecialType.None) Debug.Assert(corType.ContainingAssembly Is Me) Debug.Assert(corType.ContainingModule.Ordinal = 0) Debug.Assert(Me.CorLibrary Is Me) If (_lazySpecialTypes Is Nothing) Then Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing) End If If (Interlocked.CompareExchange(_lazySpecialTypes(typeId), corType, Nothing) IsNot Nothing) Then Debug.Assert(corType Is _lazySpecialTypes(typeId) OrElse (corType.Kind = SymbolKind.ErrorType AndAlso _lazySpecialTypes(typeId).Kind = SymbolKind.ErrorType)) Else Interlocked.Increment(_cachedSpecialTypes) Debug.Assert(_cachedSpecialTypes > 0 AndAlso _cachedSpecialTypes <= SpecialType.Count) End If End Sub ''' <summary> ''' Continue looking for declaration of predefined CorLib type in this Assembly ''' while symbols for new type declarations are constructed. ''' </summary> Friend Overrides ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean Get Return Me.CorLibrary Is Me AndAlso _cachedSpecialTypes < SpecialType.Count End Get End Property Private _lazyTypeNames As ICollection(Of String) Private _lazyNamespaceNames As ICollection(Of String) Public Overrides ReadOnly Property TypeNames As ICollection(Of String) Get If _lazyTypeNames Is Nothing Then Interlocked.CompareExchange(_lazyTypeNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.TypeNames), Nothing) End If Return _lazyTypeNames End Get End Property Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String) Get If _lazyNamespaceNames Is Nothing Then Interlocked.CompareExchange(_lazyNamespaceNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.NamespaceNames), Nothing) End If Return _lazyNamespaceNames End Get End Property ''' <summary> ''' Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. ''' Assumes that the public key has been determined. The result will be cached. ''' </summary> ''' <param name="potentialGiverOfAccess"></param> ''' <returns></returns> ''' <remarks></remarks> Protected Function MakeFinalIVTDetermination(potentialGiverOfAccess As AssemblySymbol) As IVTConclusion Dim result As IVTConclusion = IVTConclusion.NoRelationshipClaimed If AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, result) Then Return result End If result = IVTConclusion.NoRelationshipClaimed ' returns an empty list if there was no IVT attribute at all for the given name ' A name w/o a key is represented by a list with an entry that is empty Dim publicKeys As IEnumerable(Of ImmutableArray(Of Byte)) = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Me.Name) ' We have an easy out here. Suppose the assembly wanting access is ' being compiled as a module. You can only strong-name an assembly. So we are going to optimistically ' assume that it Is going to be compiled into an assembly with a matching strong name, if necessary If publicKeys.Any() AndAlso IsNetModule Then Return IVTConclusion.Match End If ' look for one that works, if none work, then return the failure for the last one examined. For Each key In publicKeys ' We pass the public key of this assembly explicitly so PerformIVTCheck does not need ' to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(Me.PublicKey, key) If result = IVTConclusion.Match Then ' Note that C# includes OrElse result = IVTConclusion.OneSignedOneNot Exit For End If Next AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result) Return result End Function 'EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant 'internals access to us to the conclusion reached. Private _assembliesToWhichInternalAccessHasBeenAnalyzed As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Private ReadOnly Property AssembliesToWhichInternalAccessHasBeenDetermined As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Get If _assembliesToWhichInternalAccessHasBeenAnalyzed Is Nothing Then Interlocked.CompareExchange(_assembliesToWhichInternalAccessHasBeenAnalyzed, New ConcurrentDictionary(Of AssemblySymbol, IVTConclusion), Nothing) End If Return _assembliesToWhichInternalAccessHasBeenAnalyzed End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents source or metadata assembly. ''' </summary> ''' <remarks></remarks> Friend MustInherit Class MetadataOrSourceAssemblySymbol Inherits NonMissingAssemblySymbol ''' <summary> ''' An array of cached Cor types defined in this assembly. ''' Lazily filled by GetSpecialType method. ''' </summary> ''' <remarks></remarks> Private _lazySpecialTypes() As NamedTypeSymbol ''' <summary> ''' How many Cor types have we cached so far. ''' </summary> Private _cachedSpecialTypes As Integer ''' <summary> ''' Lookup declaration for predefined CorLib type in this Assembly. Only should be ''' called if it is know that this is the Cor Library (mscorlib). ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol #If DEBUG Then For Each [module] In Me.Modules Debug.Assert([module].GetReferencedAssemblies().Length = 0) Next #End If If _lazySpecialTypes Is Nothing OrElse _lazySpecialTypes(type) Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim [module] As ModuleSymbol = Me.Modules(0) Dim result As NamedTypeSymbol = [module].LookupTopLevelMetadataType(emittedName) If result.TypeKind <> TypeKind.Error AndAlso result.DeclaredAccessibility <> Accessibility.Public Then result = New MissingMetadataTypeSymbol.TopLevel([module], emittedName, type) End If RegisterDeclaredSpecialType(result) End If Return _lazySpecialTypes(type) End Function ''' <summary> ''' Register declaration of predefined CorLib type in this Assembly. ''' </summary> ''' <param name="corType"></param> Friend Overrides Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol) Dim typeId As SpecialType = corType.SpecialType Debug.Assert(typeId <> SpecialType.None) Debug.Assert(corType.ContainingAssembly Is Me) Debug.Assert(corType.ContainingModule.Ordinal = 0) Debug.Assert(Me.CorLibrary Is Me) If (_lazySpecialTypes Is Nothing) Then Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing) End If If (Interlocked.CompareExchange(_lazySpecialTypes(typeId), corType, Nothing) IsNot Nothing) Then Debug.Assert(corType Is _lazySpecialTypes(typeId) OrElse (corType.Kind = SymbolKind.ErrorType AndAlso _lazySpecialTypes(typeId).Kind = SymbolKind.ErrorType)) Else Interlocked.Increment(_cachedSpecialTypes) Debug.Assert(_cachedSpecialTypes > 0 AndAlso _cachedSpecialTypes <= SpecialType.Count) End If End Sub ''' <summary> ''' Continue looking for declaration of predefined CorLib type in this Assembly ''' while symbols for new type declarations are constructed. ''' </summary> Friend Overrides ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean Get Return Me.CorLibrary Is Me AndAlso _cachedSpecialTypes < SpecialType.Count End Get End Property Private _lazyTypeNames As ICollection(Of String) Private _lazyNamespaceNames As ICollection(Of String) Public Overrides ReadOnly Property TypeNames As ICollection(Of String) Get If _lazyTypeNames Is Nothing Then Interlocked.CompareExchange(_lazyTypeNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.TypeNames), Nothing) End If Return _lazyTypeNames End Get End Property Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String) Get If _lazyNamespaceNames Is Nothing Then Interlocked.CompareExchange(_lazyNamespaceNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.NamespaceNames), Nothing) End If Return _lazyNamespaceNames End Get End Property ''' <summary> ''' Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. ''' Assumes that the public key has been determined. The result will be cached. ''' </summary> ''' <param name="potentialGiverOfAccess"></param> ''' <returns></returns> ''' <remarks></remarks> Protected Function MakeFinalIVTDetermination(potentialGiverOfAccess As AssemblySymbol) As IVTConclusion Dim result As IVTConclusion = IVTConclusion.NoRelationshipClaimed If AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, result) Then Return result End If result = IVTConclusion.NoRelationshipClaimed ' returns an empty list if there was no IVT attribute at all for the given name ' A name w/o a key is represented by a list with an entry that is empty Dim publicKeys As IEnumerable(Of ImmutableArray(Of Byte)) = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Me.Name) ' We have an easy out here. Suppose the assembly wanting access is ' being compiled as a module. You can only strong-name an assembly. So we are going to optimistically ' assume that it Is going to be compiled into an assembly with a matching strong name, if necessary If publicKeys.Any() AndAlso IsNetModule Then Return IVTConclusion.Match End If ' look for one that works, if none work, then return the failure for the last one examined. For Each key In publicKeys ' We pass the public key of this assembly explicitly so PerformIVTCheck does not need ' to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(Me.PublicKey, key) If result = IVTConclusion.Match Then ' Note that C# includes OrElse result = IVTConclusion.OneSignedOneNot Exit For End If Next AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result) Return result End Function 'EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant 'internals access to us to the conclusion reached. Private _assembliesToWhichInternalAccessHasBeenAnalyzed As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Private ReadOnly Property AssembliesToWhichInternalAccessHasBeenDetermined As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Get If _assembliesToWhichInternalAccessHasBeenAnalyzed Is Nothing Then Interlocked.CompareExchange(_assembliesToWhichInternalAccessHasBeenAnalyzed, New ConcurrentDictionary(Of AssemblySymbol, IVTConclusion), Nothing) End If Return _assembliesToWhichInternalAccessHasBeenAnalyzed End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.Operations Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")> Public Sub UsingDeclarationSyntaxNotNull() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using D1 as New C1() End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.NotNull(op.Resources.Syntax) Assert.Same(node.UsingStatement, op.Resources.Syntax) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")> Public Sub UsingDeclarationIncompleteUsingInvalidExpression() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30201: Expression expected. Using ~ </expected>) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.Equal(OperationKind.Invalid, op.Resources.Kind) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IUsingStatement_MultipleNewResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As ... s C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"Using c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleAsNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MultipleAsNewResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1, c2 As New C'BIND:"Using c1, c2 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1, c2 As New C') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1, c2 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleExistingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidMultipleExistingResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1, c2'BIND:"Using c1, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As System.Object Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1, c2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1, c2') Declarators: IVariableDeclaratorOperation (Symbol: c1 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c1' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1, c2'BIND:"Using c1, c2" ~~ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(c1) ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_NestedUsing() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1'BIND:"Using c1" Using c2 Console.WriteLine(c1) End Using End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c2 ... End Using') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c2 ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MixedAsNewAndSingleInitializer() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Local_3: c3 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c3 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2, c3 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null IVariableDeclaratorOperation (Symbol: c3 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNoInitializerOneVariable() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c2 As New C Using c1 = New C, c2'BIND:"Using c1 = New C, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 = New C, c2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c2') Declarators: IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNonDisposableResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C, IsInvalid) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'. Using c1 As New C'BIND:"Using c1 As New C" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidEmptyUsingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using'BIND:"Using" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using'BIND: ... End Using') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Using'BIND:"Using" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNothingResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using Nothing'BIND:"Using Nothing" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using Nothi ... End Using') Resources: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'. Using Nothing'BIND:"Using Nothing" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingWithoutSavedReference() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using GetC()'BIND:"Using GetC()" End Using End Sub Function GetC() As C Return New C End Function Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using GetC( ... End Using') Resources: IInvocationOperation (Function Program.GetC() As Program.C) (OperationKind.Invocation, Type: Program.C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using GetC( ... End Using') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c2 = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource() Dim source = <compilation> <file Name="a.vb"> <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"c1 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingStatementSyntax_Expression() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C Console.WriteLine()'BIND:"Console.WriteLine()" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()') Expression: IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer) 'BIND:"Sub M" Using c1 As C1 = New C1, s2 As S2 = New S2 x = 1 End Using End Sub End Class Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Structure S2 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [c1 As C1] [s2 As S2] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'c1 As C1 = New C1') Left: ILocalReferenceOperation: c1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S2, IsImplicit) (Syntax: 's2 As S2 = New S2') Left: ILocalReferenceOperation: s2 (IsDeclaration: True) (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Right: IObjectCreationOperation (Constructor: Sub S2..ctor()) (OperationKind.ObjectCreation, Type: S2) (Syntax: 'New S2') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's2') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 's2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILocalReferenceOperation: s2 (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c1') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using Nothing End Using End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Nothing') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNothingLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'Nothing') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'Nothing') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_NotDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'D' must implement 'System.IDisposable'. Using New D() ~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D, IsInvalid) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'New D()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_Missing_IDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class ]]>.Value Dim compilation = CreateCompilation(source) compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'New D()') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.Operations Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")> Public Sub UsingDeclarationSyntaxNotNull() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using D1 as New C1() End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.NotNull(op.Resources.Syntax) Assert.Same(node.UsingStatement, op.Resources.Syntax) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")> Public Sub UsingDeclarationIncompleteUsingInvalidExpression() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30201: Expression expected. Using ~ </expected>) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.Equal(OperationKind.Invalid, op.Resources.Kind) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IUsingStatement_MultipleNewResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As ... s C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"Using c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleAsNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MultipleAsNewResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1, c2 As New C'BIND:"Using c1, c2 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1, c2 As New C') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1, c2 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleExistingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidMultipleExistingResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1, c2'BIND:"Using c1, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As System.Object Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1, c2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1, c2') Declarators: IVariableDeclaratorOperation (Symbol: c1 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c1' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1, c2'BIND:"Using c1, c2" ~~ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(c1) ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_NestedUsing() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1'BIND:"Using c1" Using c2 Console.WriteLine(c1) End Using End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c2 ... End Using') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c2 ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MixedAsNewAndSingleInitializer() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Local_3: c3 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c3 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2, c3 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null IVariableDeclaratorOperation (Symbol: c3 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNoInitializerOneVariable() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c2 As New C Using c1 = New C, c2'BIND:"Using c1 = New C, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 = New C, c2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c2') Declarators: IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNonDisposableResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C, IsInvalid) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'. Using c1 As New C'BIND:"Using c1 As New C" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidEmptyUsingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using'BIND:"Using" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using'BIND: ... End Using') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Using'BIND:"Using" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNothingResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using Nothing'BIND:"Using Nothing" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using Nothi ... End Using') Resources: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'. Using Nothing'BIND:"Using Nothing" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingWithoutSavedReference() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using GetC()'BIND:"Using GetC()" End Using End Sub Function GetC() As C Return New C End Function Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using GetC( ... End Using') Resources: IInvocationOperation (Function Program.GetC() As Program.C) (OperationKind.Invocation, Type: Program.C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using GetC( ... End Using') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c2 = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource() Dim source = <compilation> <file Name="a.vb"> <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"c1 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingStatementSyntax_Expression() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C Console.WriteLine()'BIND:"Console.WriteLine()" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()') Expression: IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer) 'BIND:"Sub M" Using c1 As C1 = New C1, s2 As S2 = New S2 x = 1 End Using End Sub End Class Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Structure S2 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [c1 As C1] [s2 As S2] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'c1 As C1 = New C1') Left: ILocalReferenceOperation: c1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S2, IsImplicit) (Syntax: 's2 As S2 = New S2') Left: ILocalReferenceOperation: s2 (IsDeclaration: True) (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Right: IObjectCreationOperation (Constructor: Sub S2..ctor()) (OperationKind.ObjectCreation, Type: S2) (Syntax: 'New S2') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's2') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 's2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILocalReferenceOperation: s2 (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c1') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using Nothing End Using End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Nothing') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNothingLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'Nothing') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'Nothing') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_NotDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'D' must implement 'System.IDisposable'. Using New D() ~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D, IsInvalid) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'New D()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_Missing_IDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class ]]>.Value Dim compilation = CreateCompilation(source) compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'New D()') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList`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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct SyntaxList<TNode> : IEquatable<SyntaxList<TNode>> where TNode : GreenNode { private readonly GreenNode? _node; internal SyntaxList(GreenNode? node) { _node = node; } internal GreenNode? Node => _node; public int Count { get { return _node == null ? 0 : (_node.IsList ? _node.SlotCount : 1); } } public TNode? this[int index] { get { if (_node == null) { return null; } else if (_node.IsList) { Debug.Assert(index >= 0); Debug.Assert(index <= _node.SlotCount); return (TNode?)_node.GetSlot(index); } else if (index == 0) { return (TNode?)_node; } else { throw ExceptionUtilities.Unreachable; } } } internal TNode GetRequiredItem(int index) { var node = this[index]; RoslynDebug.Assert(node is object); return node; } internal GreenNode? ItemUntyped(int index) { RoslynDebug.Assert(_node is object); var node = this._node; if (node.IsList) { return node.GetSlot(index); } Debug.Assert(index == 0); return node; } public bool Any() { return _node != null; } public bool Any(int kind) { foreach (var element in this) { if (element.RawKind == kind) { return true; } } return false; } internal TNode[] Nodes { get { var arr = new TNode[this.Count]; for (int i = 0; i < this.Count; i++) { arr[i] = GetRequiredItem(i); } return arr; } } public TNode? Last { get { RoslynDebug.Assert(_node is object); var node = this._node; if (node.IsList) { return (TNode?)node.GetSlot(node.SlotCount - 1); } return (TNode?)node; } } public Enumerator GetEnumerator() { return new Enumerator(this); } internal void CopyTo(int offset, ArrayElement<GreenNode>[] array, int arrayOffset, int count) { for (int i = 0; i < count; i++) { array[arrayOffset + i].Value = GetRequiredItem(i + offset); } } public static bool operator ==(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node == right._node; } public static bool operator !=(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node != right._node; } public bool Equals(SyntaxList<TNode> other) { return _node == other._node; } public override bool Equals(object? obj) { return (obj is SyntaxList<TNode>) && Equals((SyntaxList<TNode>)obj); } public override int GetHashCode() { return _node != null ? _node.GetHashCode() : 0; } public SeparatedSyntaxList<TOther> AsSeparatedList<TOther>() where TOther : GreenNode { return new SeparatedSyntaxList<TOther>(this); } public static implicit operator SyntaxList<TNode>(TNode node) { return new SyntaxList<TNode>(node); } public static implicit operator SyntaxList<TNode>(SyntaxList<GreenNode> nodes) { return new SyntaxList<TNode>(nodes._node); } public static implicit operator SyntaxList<GreenNode>(SyntaxList<TNode> nodes) { return new SyntaxList<GreenNode>(nodes.Node); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct SyntaxList<TNode> : IEquatable<SyntaxList<TNode>> where TNode : GreenNode { private readonly GreenNode? _node; internal SyntaxList(GreenNode? node) { _node = node; } internal GreenNode? Node => _node; public int Count { get { return _node == null ? 0 : (_node.IsList ? _node.SlotCount : 1); } } public TNode? this[int index] { get { if (_node == null) { return null; } else if (_node.IsList) { Debug.Assert(index >= 0); Debug.Assert(index <= _node.SlotCount); return (TNode?)_node.GetSlot(index); } else if (index == 0) { return (TNode?)_node; } else { throw ExceptionUtilities.Unreachable; } } } internal TNode GetRequiredItem(int index) { var node = this[index]; RoslynDebug.Assert(node is object); return node; } internal GreenNode? ItemUntyped(int index) { RoslynDebug.Assert(_node is object); var node = this._node; if (node.IsList) { return node.GetSlot(index); } Debug.Assert(index == 0); return node; } public bool Any() { return _node != null; } public bool Any(int kind) { foreach (var element in this) { if (element.RawKind == kind) { return true; } } return false; } internal TNode[] Nodes { get { var arr = new TNode[this.Count]; for (int i = 0; i < this.Count; i++) { arr[i] = GetRequiredItem(i); } return arr; } } public TNode? Last { get { RoslynDebug.Assert(_node is object); var node = this._node; if (node.IsList) { return (TNode?)node.GetSlot(node.SlotCount - 1); } return (TNode?)node; } } public Enumerator GetEnumerator() { return new Enumerator(this); } internal void CopyTo(int offset, ArrayElement<GreenNode>[] array, int arrayOffset, int count) { for (int i = 0; i < count; i++) { array[arrayOffset + i].Value = GetRequiredItem(i + offset); } } public static bool operator ==(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node == right._node; } public static bool operator !=(SyntaxList<TNode> left, SyntaxList<TNode> right) { return left._node != right._node; } public bool Equals(SyntaxList<TNode> other) { return _node == other._node; } public override bool Equals(object? obj) { return (obj is SyntaxList<TNode>) && Equals((SyntaxList<TNode>)obj); } public override int GetHashCode() { return _node != null ? _node.GetHashCode() : 0; } public SeparatedSyntaxList<TOther> AsSeparatedList<TOther>() where TOther : GreenNode { return new SeparatedSyntaxList<TOther>(this); } public static implicit operator SyntaxList<TNode>(TNode node) { return new SyntaxList<TNode>(node); } public static implicit operator SyntaxList<TNode>(SyntaxList<GreenNode> nodes) { return new SyntaxList<TNode>(nodes._node); } public static implicit operator SyntaxList<GreenNode>(SyntaxList<TNode> nodes) { return new SyntaxList<GreenNode>(nodes.Node); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeFunctionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeFunctionTests Inherits AbstractCodeFunctionTests #Region "Get Start Point" <WorkItem(1980, "https://github.com/dotnet/roslyn/issues/1980")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPointConversionOperatorFunction() Dim code = <Code> class D { public static implicit operator $$D(double d) { return new D(); } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=65, lineLength:=23))) End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPointExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=8, lineOffset:=5, absoluteOffset:=67, lineLength:=15))) End Sub #End Region #Region "Get End Point" <WorkItem(1980, "https://github.com/dotnet/roslyn/issues/1980")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPointConversionOperatorFunction() Dim code = <Code> class D { public static implicit operator $$D(double d) { return new D(); } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=89, lineLength:=5))) End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPointExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=11, lineOffset:=6, absoluteOffset:=108, lineLength:=5))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> interface I { int $$Goo(); } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attribute Tests" <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertyGetAttribute_WithNoSet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$get { return 0; } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertySetAttribute_WithNoGet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertyGetAttribute_WithSet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$get { return 0; } [Obsolete] set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertySetAttribute_WithGet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] get { return 0; } [Obsolete] $$set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttribute_1() Dim code = <Code> class Class2 { [Obsolete] void $$F() { } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub #End Region #Region "CanOverride tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride1() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride2() Dim code = <Code> interface I { void $$Goo(); } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride3() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride4() Dim code = <Code> class C { protected void $$Goo() { } } </Code> TestCanOverride(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride5() Dim code = <Code> class B { protected virtual void Goo() { } } class C : B { protected override void $$Goo() { base.Goo(); } } </Code> TestCanOverride(code, False) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestFullName(code, "C.~C") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestFullName(code, "C1.I1.f1") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ImplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.implicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ExplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.explicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_OperatorOverload() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator $$+(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.operator +") End Sub #End Region #Region "FunctionKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionDestructor) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ExplicitInterfaceImplementation() Dim code = <Code> public interface I1 { void f1(); } public class C1: I1 { void I1.f1$$() { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_Operator() Dim code = <Code> public class C { public static C operator $$+(C c1, C c2) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ExplicitConversion() Dim code = <Code> public class C { public static static $$explicit C(int x) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ImplicitConversion() Dim code = <Code> public class C { public static static $$implicit C(int x) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub #End Region #Region "MustImplement tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement1() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestMustImplement(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement2() Dim code = <Code> interface I { void $$Goo(); } </Code> TestMustImplement(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement3() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestMustImplement(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement4() Dim code = <Code> class C { protected void $$Goo() { } } </Code> TestMustImplement(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement5() Dim code = <Code> class B { protected virtual void Goo() { } } class C : B { protected override void $$Goo() { base.Goo(); } } </Code> TestMustImplement(code, False) End Sub #End Region #Region "Name tests" <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestName(code, "I1.f1") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestName(code, "~C") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ImplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "implicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ExplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "explicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_OperatorOverload() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator $$+(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "operator +") End Sub #End Region #Region "OverrideKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> class C { protected sealed void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> abstract class B { protected abstract void Goo(); } class C : B { protected override void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_New() Dim code = <Code> abstract class B { protected void Goo(); } class C : B { protected new void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew) End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullNameOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_UniqueSignature() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.MethodC(int,bool)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ParamTypesOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeParamTypes, "MethodC (int, bool)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ParamNamesOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeParamNames, "MethodC (intA, boolB)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ReturnType() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "bool MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName1() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName2() Dim code = <Code> class A&lt;T&gt; { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A<>.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName3() Dim code = <Code> class C&lt;T&gt; { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C<>.A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName4() Dim code = <Code> class C { class A&lt;T&gt; { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.A<>.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName5() Dim code = <Code> class C { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName6() Dim code = <Code> namespace N { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_Unique() Dim code = <Code> class A { public $$A() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.#ctor()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_Unique() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.#dtor()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Unique_InvalidCombination() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototypeThrows(Of ArgumentException)(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_FullName() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_FullName() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_FullName() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.operator +") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_ReturnType() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "void A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_ReturnType() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "void ~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_ReturnType() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "A operator +") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_ClassName() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_ClassName() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_ClassName() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.operator +") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Constructor() Dim code = <Code> class A { public $$A() { } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "System.Void", .AsString = "void", .CodeTypeFullName = "System.Void", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Finalizer() Dim code = <Code> class A { $$~A() { } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "System.Void", .AsString = "void", .CodeTypeFullName = "System.Void", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Operator() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "A", .AsString = "A", .CodeTypeFullName = "A", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType }) End Sub #End Region #Region "RemoveParameter tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter1() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M() { } } </Code> Await TestRemoveChild(code, expected, "a") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter2() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(int a) { } } </Code> Await TestRemoveChild(code, expected, "b") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter3() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(string b) { } } </Code> Await TestRemoveChild(code, expected, "a") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter4() As Task Dim code = <Code> class C { void $$M(int a, string b, int c) { } } </Code> Dim expected = <Code> class C { void M(int a, int c) { } } </Code> Await TestRemoveChild(code, expected, "b") End Function #End Region #Region "AddParameter tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter1() As Task Dim code = <Code> class C { void $$M() { } } </Code> Dim expected = <Code> class C { void M(int a) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "a", .Type = "int"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter2() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M(string b, int a) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "string"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter3() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(int a, bool c, string b) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "c", .Type = "System.Boolean", .Position = 1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter4() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M(int a, string b) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "string", .Position = -1}) End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { public int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { internal int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { protected internal int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { public int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { protected internal int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> interface I { int $$Goo(); } </Code> Dim expected = <Code> interface I { int Goo(); } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> interface I { int $$Goo(); } </Code> Dim expected = <Code> interface I { int Goo(); } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { static void Goo() { } } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared3() As Task Dim code = <Code> class C { $$C() { } } </Code> Dim expected = <Code> class C { static C() { } } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared4() As Task Dim code = <Code> class C { static $$C() { } } </Code> Dim expected = <Code> class C { C() { } } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set CanOverride tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride2() As Task Dim code = <Code> class C { virtual void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride3() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetCanOverride(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride4() As Task Dim code = <Code> class C { virtual void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetCanOverride(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride5() As Task Dim code = <Code> interface I { void $$Goo(); } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride6() As Task Dim code = <Code> interface I { void $$Goo(); } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestSetCanOverride(code, expected, False, ThrowsArgumentException(Of Boolean)) End Function #End Region #Region "Set MustImplement tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement1() As Task Dim code = <Code> abstract class C { abstract void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement2() As Task Dim code = <Code> abstract class C { void $$Goo() { int i = 0; } } </Code> Dim expected = <Code> abstract class C { abstract void Goo() { int i = 0; } } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement3() As Task Dim code = <Code> abstract class C { abstract void $$Goo(); } </Code> Dim expected = <Code> abstract class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement4() As Task Dim code = <Code> abstract class C { abstract void $$Goo(); } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement5() As Task Dim code = <Code> abstract class C { void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement6() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, True, ThrowsArgumentException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement7() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement8() As Task Dim code = <Code> interface I { void $$Goo() { } } </Code> Dim expected = <Code> interface I { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False, ThrowsArgumentException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement9() As Task Dim code = <Code> interface I { void $$Goo() { } } </Code> Dim expected = <Code> interface I { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, True) End Function #End Region #Region "Set OverrideKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind2() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { sealed void Goo() { } } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind3() As Task Dim code = <Code> abstract class C { void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Bar() { } } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { int Goo() { } } </Code> Await TestSetTypeProp(code, expected, "System.Int32") End Function #End Region #Region "ExtensionMethodExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExtensionMethodExtender_IsExtension1() Dim code = <Code> public static class C { public static void $$Goo(this C c) { } } </Code> TestExtensionMethodExtender_IsExtension(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExtensionMethodExtender_IsExtension2() Dim code = <Code> public static class C { public static void $$Goo(C c) { } } </Code> TestExtensionMethodExtender_IsExtension(code, False) End Sub #End Region #Region "PartialMethodExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart4() Dim code = <Code> public partial class C { partial void $$M(); } </Code> TestPartialMethodExtender_HasOtherPart(code, False) End Sub #End Region #Region "Overloads Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads1() Dim code = <Code> public static class C { public static void $$Goo() { } public static void Goo(C c) { } } </Code> TestOverloadsUniqueSignatures(code, "C.Goo()", "C.Goo(C)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads2() Dim code = <Code> public static class C { public static void $$Goo() { } } </Code> TestOverloadsUniqueSignatures(code, "C.Goo()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads3() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestOverloadsUniqueSignatures(code, "A.#op_Plus(A,A)") End Sub #End Region #Region "Parameter name tests" <WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters() Dim code = <Code> public class C { public void $$Goo(int @int) { } } </Code> TestAllParameterNames(code, "@int") End Sub <WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters_2() Dim code = <Code> public class C { public void $$Goo(int @int, string @string) { } } </Code> TestAllParameterNames(code, "@int", "@string") End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { void $$M() { } } </Code> Dim expected = <Code> using System; class C { [Serializable()] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] void $$M() { } } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; void $$M() { } } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class C { void $$M() { } } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeFunction2)(code) End Sub Private Function GetExtensionMethodExtender(codeElement As EnvDTE80.CodeFunction2) As ICSExtensionMethodExtender Return CType(codeElement.Extender(ExtenderNames.ExtensionMethod), ICSExtensionMethodExtender) End Function Private Function GetPartialMethodExtender(codeElement As EnvDTE80.CodeFunction2) As ICSPartialMethodExtender Return CType(codeElement.Extender(ExtenderNames.PartialMethod), ICSPartialMethodExtender) End Function Protected Overrides Function ExtensionMethodExtender_GetIsExtension(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetExtensionMethodExtender(codeElement).IsExtension End Function Protected Overrides Function PartialMethodExtender_GetIsPartial(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsPartial End Function Protected Overrides Function PartialMethodExtender_GetIsDeclaration(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsDeclaration End Function Protected Overrides Function PartialMethodExtender_GetHasOtherPart(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).HasOtherPart End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeFunctionTests Inherits AbstractCodeFunctionTests #Region "Get Start Point" <WorkItem(1980, "https://github.com/dotnet/roslyn/issues/1980")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPointConversionOperatorFunction() Dim code = <Code> class D { public static implicit operator $$D(double d) { return new D(); } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=5, lineOffset:=1, absoluteOffset:=65, lineLength:=23))) End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPointExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=8, lineOffset:=5, absoluteOffset:=67, lineLength:=15))) End Sub #End Region #Region "Get End Point" <WorkItem(1980, "https://github.com/dotnet/roslyn/issues/1980")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPointConversionOperatorFunction() Dim code = <Code> class D { public static implicit operator $$D(double d) { return new D(); } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=6, lineOffset:=1, absoluteOffset:=89, lineLength:=5))) End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPointExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=11, lineOffset:=6, absoluteOffset:=108, lineLength:=5))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$F() { throw new System.NotImplementedException(); } } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> interface I { int $$Goo(); } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attribute Tests" <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertyGetAttribute_WithNoSet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$get { return 0; } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertySetAttribute_WithNoGet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertyGetAttribute_WithSet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] $$get { return 0; } [Obsolete] set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPropertySetAttribute_WithGet() Dim code = <Code> public class Class1 { public int Property1 { [Obsolete] get { return 0; } [Obsolete] $$set { } } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub <WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttribute_1() Dim code = <Code> class Class2 { [Obsolete] void $$F() { } } </Code> TestAttributes(code, IsElement("Obsolete")) End Sub #End Region #Region "CanOverride tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride1() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride2() Dim code = <Code> interface I { void $$Goo(); } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride3() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestCanOverride(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride4() Dim code = <Code> class C { protected void $$Goo() { } } </Code> TestCanOverride(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCanOverride5() Dim code = <Code> class B { protected virtual void Goo() { } } class C : B { protected override void $$Goo() { base.Goo(); } } </Code> TestCanOverride(code, False) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestFullName(code, "C.~C") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestFullName(code, "C1.I1.f1") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ImplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.implicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_ExplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.explicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName_OperatorOverload() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator $$+(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestFullName(code, "ComplexType.operator +") End Sub #End Region #Region "FunctionKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionDestructor) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ExplicitInterfaceImplementation() Dim code = <Code> public interface I1 { void f1(); } public class C1: I1 { void I1.f1$$() { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_Operator() Dim code = <Code> public class C { public static C operator $$+(C c1, C c2) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ExplicitConversion() Dim code = <Code> public class C { public static static $$explicit C(int x) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFunctionKind_ImplicitConversion() Dim code = <Code> public class C { public static static $$implicit C(int x) { } } </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub #End Region #Region "MustImplement tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement1() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestMustImplement(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement2() Dim code = <Code> interface I { void $$Goo(); } </Code> TestMustImplement(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement3() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestMustImplement(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement4() Dim code = <Code> class C { protected void $$Goo() { } } </Code> TestMustImplement(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestMustImplement5() Dim code = <Code> class B { protected virtual void Goo() { } } class C : B { protected override void $$Goo() { base.Goo(); } } </Code> TestMustImplement(code, False) End Sub #End Region #Region "Name tests" <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ExplicitlyImplementedMethod() Dim code = <Code> public interface I1 { int f1(); } public class C1 : I1 { int I1.f1$$() { return 0; } } </Code> TestName(code, "I1.f1") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_Destructor() Dim code = <Code> class C { ~C$$() { } } </Code> TestName(code, "~C") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ImplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "implicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_ExplicitOperator() Dim code = <Code> public class ComplexType { public ComplexType() { } public static explicit operator $$ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator +(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "explicit operator ComplexType") End Sub <WorkItem(2437, "https://github.com/dotnet/roslyn/issues/2437")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName_OperatorOverload() Dim code = <Code> public class ComplexType { public ComplexType() { } public static implicit operator ComplexType(System.Int32 input) { return new ComplexType(); } public static ComplexType operator $$+(ComplexType input0, ComplexType input1) { return default(ComplexType); } } </Code> TestName(code, "operator +") End Sub #End Region #Region "OverrideKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> abstract class C { protected abstract void $$Goo(); } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> class C { protected virtual void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> class C { protected sealed void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> abstract class B { protected abstract void Goo(); } class C : B { protected override void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_New() Dim code = <Code> abstract class B { protected void Goo(); } class C : B { protected new void $$Goo() { } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew) End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullNameOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_UniqueSignature() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.MethodC(int,bool)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ParamTypesOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeParamTypes, "MethodC (int, bool)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ParamNamesOnly() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeParamNames, "MethodC (intA, boolB)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ReturnType() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "bool MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName1() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName2() Dim code = <Code> class A&lt;T&gt; { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A<>.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName3() Dim code = <Code> class C&lt;T&gt; { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C<>.A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName4() Dim code = <Code> class C { class A&lt;T&gt; { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.A<>.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName5() Dim code = <Code> class C { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName6() Dim code = <Code> namespace N { class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.MethodC") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_Unique() Dim code = <Code> class A { public $$A() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.#ctor()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_Unique() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "A.#dtor()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Unique_InvalidCombination() Dim code = <Code> class A { internal static bool $$MethodC(int intA, bool boolB) { return boolB; } } </Code> TestPrototypeThrows(Of ArgumentException)(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_FullName() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_FullName() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_FullName() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "A.operator +") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_ReturnType() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "void A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_ReturnType() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "void ~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_ReturnType() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "A operator +") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Constructor_ClassName() Dim code = <Code> class A { public A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Finalizer_ClassName() Dim code = <Code> class A { ~A$$() { } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.~A") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_Operator_ClassName() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "A.operator +") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Constructor() Dim code = <Code> class A { public $$A() { } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "System.Void", .AsString = "void", .CodeTypeFullName = "System.Void", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Finalizer() Dim code = <Code> class A { $$~A() { } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "System.Void", .AsString = "void", .CodeTypeFullName = "System.Void", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType_Operator() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsFullName = "A", .AsString = "A", .CodeTypeFullName = "A", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType }) End Sub #End Region #Region "RemoveParameter tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter1() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M() { } } </Code> Await TestRemoveChild(code, expected, "a") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter2() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(int a) { } } </Code> Await TestRemoveChild(code, expected, "b") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter3() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(string b) { } } </Code> Await TestRemoveChild(code, expected, "a") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemoveParameter4() As Task Dim code = <Code> class C { void $$M(int a, string b, int c) { } } </Code> Dim expected = <Code> class C { void M(int a, int c) { } } </Code> Await TestRemoveChild(code, expected, "b") End Function #End Region #Region "AddParameter tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter1() As Task Dim code = <Code> class C { void $$M() { } } </Code> Dim expected = <Code> class C { void M(int a) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "a", .Type = "int"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter2() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M(string b, int a) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "string"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter3() As Task Dim code = <Code> class C { void $$M(int a, string b) { } } </Code> Dim expected = <Code> class C { void M(int a, bool c, string b) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "c", .Type = "System.Boolean", .Position = 1}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddParameter4() As Task Dim code = <Code> class C { void $$M(int a) { } } </Code> Dim expected = <Code> class C { void M(int a, string b) { } } </Code> Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "string", .Position = -1}) End Function #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { public int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { internal int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { protected internal int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { public int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { protected internal int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$Goo() { throw new System.NotImplementedException(); } } </Code> Dim expected = <Code> class C { int Goo() { throw new System.NotImplementedException(); } } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> interface I { int $$Goo(); } </Code> Dim expected = <Code> interface I { int Goo(); } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> interface I { int $$Goo(); } </Code> Dim expected = <Code> interface I { int Goo(); } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { static void Goo() { } } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetIsShared(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared3() As Task Dim code = <Code> class C { $$C() { } } </Code> Dim expected = <Code> class C { static C() { } } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared4() As Task Dim code = <Code> class C { static $$C() { } } </Code> Dim expected = <Code> class C { C() { } } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set CanOverride tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride2() As Task Dim code = <Code> class C { virtual void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride3() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetCanOverride(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride4() As Task Dim code = <Code> class C { virtual void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetCanOverride(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride5() As Task Dim code = <Code> interface I { void $$Goo(); } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestSetCanOverride(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetCanOverride6() As Task Dim code = <Code> interface I { void $$Goo(); } </Code> Dim expected = <Code> interface I { void Goo(); } </Code> Await TestSetCanOverride(code, expected, False, ThrowsArgumentException(Of Boolean)) End Function #End Region #Region "Set MustImplement tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement1() As Task Dim code = <Code> abstract class C { abstract void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement2() As Task Dim code = <Code> abstract class C { void $$Goo() { int i = 0; } } </Code> Dim expected = <Code> abstract class C { abstract void Goo() { int i = 0; } } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement3() As Task Dim code = <Code> abstract class C { abstract void $$Goo(); } </Code> Dim expected = <Code> abstract class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement4() As Task Dim code = <Code> abstract class C { abstract void $$Goo(); } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetMustImplement(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement5() As Task Dim code = <Code> abstract class C { void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement6() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, True, ThrowsArgumentException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement7() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement8() As Task Dim code = <Code> interface I { void $$Goo() { } } </Code> Dim expected = <Code> interface I { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, False, ThrowsArgumentException(Of Boolean)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetMustImplement9() As Task Dim code = <Code> interface I { void $$Goo() { } } </Code> Dim expected = <Code> interface I { void Goo() { } } </Code> Await TestSetMustImplement(code, expected, True) End Function #End Region #Region "Set OverrideKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { virtual void Goo() { } } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind2() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { sealed void Goo() { } } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetOverrideKind3() As Task Dim code = <Code> abstract class C { void $$Goo() { } } </Code> Dim expected = <Code> abstract class C { abstract void Goo(); } </Code> Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { void Bar() { } } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { void $$Goo() { } } </Code> Dim expected = <Code> class C { int Goo() { } } </Code> Await TestSetTypeProp(code, expected, "System.Int32") End Function #End Region #Region "ExtensionMethodExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExtensionMethodExtender_IsExtension1() Dim code = <Code> public static class C { public static void $$Goo(this C c) { } } </Code> TestExtensionMethodExtender_IsExtension(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestExtensionMethodExtender_IsExtension2() Dim code = <Code> public static class C { public static void $$Goo(C c) { } } </Code> TestExtensionMethodExtender_IsExtension(code, False) End Sub #End Region #Region "PartialMethodExtender" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsPartial3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_IsPartial(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_IsDeclaration3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart1() Dim code = <Code> public partial class C { partial void $$M(); partial void M() { } void M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart2() Dim code = <Code> public partial class C { partial void M(); partial void $$M() { } void M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart3() Dim code = <Code> public partial class C { partial void M(); partial void M() { } void $$M(int i) { } } </Code> TestPartialMethodExtender_HasOtherPart(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPartialMethodExtender_HasOtherPart4() Dim code = <Code> public partial class C { partial void $$M(); } </Code> TestPartialMethodExtender_HasOtherPart(code, False) End Sub #End Region #Region "Overloads Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads1() Dim code = <Code> public static class C { public static void $$Goo() { } public static void Goo(C c) { } } </Code> TestOverloadsUniqueSignatures(code, "C.Goo()", "C.Goo(C)") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads2() Dim code = <Code> public static class C { public static void $$Goo() { } } </Code> TestOverloadsUniqueSignatures(code, "C.Goo()") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads3() Dim code = <Code> class A { public static A operator +$$(A a1, A a2) { return a1; } } </Code> TestOverloadsUniqueSignatures(code, "A.#op_Plus(A,A)") End Sub #End Region #Region "Parameter name tests" <WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters() Dim code = <Code> public class C { public void $$Goo(int @int) { } } </Code> TestAllParameterNames(code, "@int") End Sub <WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters_2() Dim code = <Code> public class C { public void $$Goo(int @int, string @string) { } } </Code> TestAllParameterNames(code, "@int", "@string") End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { void $$M() { } } </Code> Dim expected = <Code> using System; class C { [Serializable()] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] void $$M() { } } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; void $$M() { } } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] void M() { } } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class C { void $$M() { } } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeFunction2)(code) End Sub Private Function GetExtensionMethodExtender(codeElement As EnvDTE80.CodeFunction2) As ICSExtensionMethodExtender Return CType(codeElement.Extender(ExtenderNames.ExtensionMethod), ICSExtensionMethodExtender) End Function Private Function GetPartialMethodExtender(codeElement As EnvDTE80.CodeFunction2) As ICSPartialMethodExtender Return CType(codeElement.Extender(ExtenderNames.PartialMethod), ICSPartialMethodExtender) End Function Protected Overrides Function ExtensionMethodExtender_GetIsExtension(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetExtensionMethodExtender(codeElement).IsExtension End Function Protected Overrides Function PartialMethodExtender_GetIsPartial(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsPartial End Function Protected Overrides Function PartialMethodExtender_GetIsDeclaration(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsDeclaration End Function Protected Overrides Function PartialMethodExtender_GetHasOtherPart(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).HasOtherPart End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioProjectTests/WorkspaceChangedEventTests.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.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class WorkspaceChangedEventTests <WpfTheory> <CombinatorialData> Public Async Function AddingASingleSourceFileRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddSourceFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.DocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single(), change.DocumentId) End Using End Function <WpfFact> Public Async Function AddingTwoDocumentsInBatchRaisesProjectChanged() As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using project.CreateBatchScope() project.AddSourceFile("Z:\Test1.vb") project.AddSourceFile("Z:\Test2.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleAdditionalFileInABatchRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddAdditionalFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.AdditionalDocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().AdditionalDocumentIds.Single(), change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleMetadataReferenceRaisesProjectChanged(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddMetadataReference("Z:\Test.dll", MetadataReferenceProperties.Assembly) End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfFact> <WorkItem(34309, "https://github.com/dotnet/roslyn/issues/34309")> Public Async Function StartingAndEndingBatchWithNoChangesDoesNothing() As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Dim startingSolution = environment.Workspace.CurrentSolution project.CreateBatchScope().Dispose() Assert.Empty(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Same(startingSolution, environment.Workspace.CurrentSolution) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class WorkspaceChangedEventTests <WpfTheory> <CombinatorialData> Public Async Function AddingASingleSourceFileRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddSourceFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.DocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single(), change.DocumentId) End Using End Function <WpfFact> Public Async Function AddingTwoDocumentsInBatchRaisesProjectChanged() As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using project.CreateBatchScope() project.AddSourceFile("Z:\Test1.vb") project.AddSourceFile("Z:\Test2.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleAdditionalFileInABatchRaisesDocumentAdded(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddAdditionalFile("Z:\Test.vb") End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.AdditionalDocumentAdded, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Equal(environment.Workspace.CurrentSolution.Projects.Single().AdditionalDocumentIds.Single(), change.DocumentId) End Using End Function <WpfTheory> <CombinatorialData> Public Async Function AddingASingleMetadataReferenceRaisesProjectChanged(addInBatch As Boolean) As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Using If(addInBatch, project.CreateBatchScope(), Nothing) project.AddMetadataReference("Z:\Test.dll", MetadataReferenceProperties.Assembly) End Using Dim change = Assert.Single(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Equal(WorkspaceChangeKind.ProjectChanged, change.Kind) Assert.Equal(project.Id, change.ProjectId) Assert.Null(change.DocumentId) End Using End Function <WpfFact> <WorkItem(34309, "https://github.com/dotnet/roslyn/issues/34309")> Public Async Function StartingAndEndingBatchWithNoChangesDoesNothing() As Task Using environment = New TestEnvironment() Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "Project", LanguageNames.CSharp, CancellationToken.None) Dim workspaceChangeEvents = New WorkspaceChangeWatcher(environment) Dim startingSolution = environment.Workspace.CurrentSolution project.CreateBatchScope().Dispose() Assert.Empty(Await workspaceChangeEvents.GetNewChangeEventsAsync()) Assert.Same(startingSolution, environment.Workspace.CurrentSolution) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/TestUtilities/TodoComments/AbtractTodoCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.TodoComments { public abstract class AbstractTodoCommentTests { protected const string DefaultTokenList = "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0"; protected abstract TestWorkspace CreateWorkspace(string codeWithMarker); protected async Task TestAsync(string codeWithMarker) { using var workspace = CreateWorkspace(codeWithMarker); var hostDocument = workspace.Documents.First(); var initialTextSnapshot = hostDocument.GetTextBuffer().CurrentSnapshot; var documentId = hostDocument.Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = document.GetLanguageService<ITodoCommentService>(); var todoComments = await service.GetTodoCommentsAsync(document, TodoCommentDescriptor.Parse(workspace.Options.GetOption(TodoCommentOptions.TokenList)), CancellationToken.None); using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync(document, todoComments, converted, CancellationToken.None); var expectedLists = hostDocument.SelectedSpans; Assert.Equal(converted.Count, expectedLists.Count); var sourceText = await document.GetTextAsync(); var tree = await document.GetSyntaxTreeAsync(); for (var i = 0; i < converted.Count; i++) { var todo = converted[i]; var span = expectedLists[i]; var line = initialTextSnapshot.GetLineFromPosition(span.Start); var text = initialTextSnapshot.GetText(span.ToSpan()); Assert.Equal(todo.MappedLine, line.LineNumber); Assert.Equal(todo.MappedColumn, span.Start - line.Start); Assert.Equal(todo.Message, text); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.TodoComments { public abstract class AbstractTodoCommentTests { protected const string DefaultTokenList = "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0"; protected abstract TestWorkspace CreateWorkspace(string codeWithMarker); protected async Task TestAsync(string codeWithMarker) { using var workspace = CreateWorkspace(codeWithMarker); var hostDocument = workspace.Documents.First(); var initialTextSnapshot = hostDocument.GetTextBuffer().CurrentSnapshot; var documentId = hostDocument.Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = document.GetLanguageService<ITodoCommentService>(); var todoComments = await service.GetTodoCommentsAsync(document, TodoCommentDescriptor.Parse(workspace.Options.GetOption(TodoCommentOptions.TokenList)), CancellationToken.None); using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync(document, todoComments, converted, CancellationToken.None); var expectedLists = hostDocument.SelectedSpans; Assert.Equal(converted.Count, expectedLists.Count); var sourceText = await document.GetTextAsync(); var tree = await document.GetSyntaxTreeAsync(); for (var i = 0; i < converted.Count; i++) { var todo = converted[i]; var span = expectedLists[i]; var line = initialTextSnapshot.GetLineFromPosition(span.Start); var text = initialTextSnapshot.GetText(span.ToSpan()); Assert.Equal(todo.MappedLine, line.LineNumber); Assert.Equal(todo.MappedColumn, span.Start - line.Start); Assert.Equal(todo.Message, text); } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/Portable/Log/IErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ErrorLogger { internal interface IErrorLoggerService : IWorkspaceService { void LogException(object source, Exception exception); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ErrorLogger { internal interface IErrorLoggerService : IWorkspaceService { void LogException(object source, Exception exception); } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/Core/Portable/Workspace/CompileTimeSolutionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provides a compile-time view of the current workspace solution. /// Workaround for Razor projects which generate both design-time and compile-time source files. /// TODO: remove https://github.com/dotnet/roslyn/issues/51678 /// </summary> internal sealed class CompileTimeSolutionProvider : ICompileTimeSolutionProvider { [ExportWorkspaceServiceFactory(typeof(ICompileTimeSolutionProvider), WorkspaceKind.Host), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new CompileTimeSolutionProvider(workspaceServices.Workspace); } private const string RazorEncConfigFileName = "RazorSourceGenerator.razorencconfig"; private const string RazorSourceGeneratorAssemblyName = "Microsoft.NET.Sdk.Razor.SourceGenerators"; private const string RazorSourceGeneratorTypeName = "Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator"; private static readonly string s_razorSourceGeneratorFileNamePrefix = Path.Combine(RazorSourceGeneratorAssemblyName, RazorSourceGeneratorTypeName); private readonly Workspace _workspace; private readonly object _gate = new(); /// <summary> /// Cached compile time solution corresponding to the <see cref="Workspace.PrimaryBranchId"/> /// </summary> private (int DesignTimeSolutionVersion, BranchId DesignTimeSolutionBranch, Solution CompileTimeSolution)? _primaryBranchCompileTimeCache; /// <summary> /// Cached compile time solution for a forked branch. This is used primarily by LSP cases where /// we fork the workspace solution and request diagnostics for the forked solution. /// </summary> private (int DesignTimeSolutionVersion, BranchId DesignTimeSolutionBranch, Solution CompileTimeSolution)? _forkedBranchCompileTimeCache; public CompileTimeSolutionProvider(Workspace workspace) { workspace.WorkspaceChanged += (s, e) => { if (e.Kind is WorkspaceChangeKind.SolutionCleared or WorkspaceChangeKind.SolutionRemoved) { lock (_gate) { _primaryBranchCompileTimeCache = null; _forkedBranchCompileTimeCache = null; } } }; _workspace = workspace; } private static bool IsRazorAnalyzerConfig(TextDocumentState documentState) => documentState.FilePath != null && documentState.FilePath.EndsWith(RazorEncConfigFileName, StringComparison.OrdinalIgnoreCase); public Solution GetCompileTimeSolution(Solution designTimeSolution) { lock (_gate) { var cachedCompileTimeSolution = GetCachedCompileTimeSolution(designTimeSolution); // Design time solution hasn't changed since we calculated the last compile-time solution: if (cachedCompileTimeSolution != null) { return cachedCompileTimeSolution; } using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var configIdsToRemove); using var _2 = ArrayBuilder<DocumentId>.GetInstance(out var documentIdsToRemove); foreach (var (_, projectState) in designTimeSolution.State.ProjectStates) { var anyConfigs = false; foreach (var (_, configState) in projectState.AnalyzerConfigDocumentStates.States) { if (IsRazorAnalyzerConfig(configState)) { configIdsToRemove.Add(configState.Id); anyConfigs = true; } } // only remove design-time only documents when source-generated ones replace them if (anyConfigs) { foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.Attributes.DesignTimeOnly) { documentIdsToRemove.Add(documentState.Id); } } } } var compileTimeSolution = designTimeSolution .RemoveAnalyzerConfigDocuments(configIdsToRemove.ToImmutable()) .RemoveDocuments(documentIdsToRemove.ToImmutable()); UpdateCachedCompileTimeSolution(designTimeSolution, compileTimeSolution); return compileTimeSolution; } } private Solution? GetCachedCompileTimeSolution(Solution designTimeSolution) { // If the design time solution is for the primary branch, retrieve the last cached solution for it. // Otherwise this is a forked solution, so retrieve the last forked compile time solution we calculated. var cachedCompileTimeSolution = designTimeSolution.BranchId == _workspace.PrimaryBranchId ? _primaryBranchCompileTimeCache : _forkedBranchCompileTimeCache; // Verify that the design time solution has not changed since the last calculated compile time solution and that // the design time solution branch matches the branch of the design time solution we calculated the compile time solution for. if (cachedCompileTimeSolution != null && designTimeSolution.WorkspaceVersion == cachedCompileTimeSolution.Value.DesignTimeSolutionVersion && designTimeSolution.BranchId == cachedCompileTimeSolution.Value.DesignTimeSolutionBranch) { return cachedCompileTimeSolution.Value.CompileTimeSolution; } return null; } private void UpdateCachedCompileTimeSolution(Solution designTimeSolution, Solution compileTimeSolution) { if (designTimeSolution.BranchId == _workspace.PrimaryBranchId) { _primaryBranchCompileTimeCache = (designTimeSolution.WorkspaceVersion, designTimeSolution.BranchId, compileTimeSolution); } else { _forkedBranchCompileTimeCache = (designTimeSolution.WorkspaceVersion, designTimeSolution.BranchId, compileTimeSolution); } } // Copied from // https://github.com/dotnet/sdk/blob/main/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs#L32 private static string GetIdentifierFromPath(string filePath) { var builder = new StringBuilder(filePath.Length); for (var i = 0; i < filePath.Length; i++) { switch (filePath[i]) { case ':' or '\\' or '/': case char ch when !char.IsLetterOrDigit(ch): builder.Append('_'); break; default: builder.Append(filePath[i]); break; } } return builder.ToString(); } private static bool IsRazorDesignTimeDocument(DocumentState documentState) => documentState.Attributes.DesignTimeOnly && documentState.FilePath?.EndsWith(".razor.g.cs") == true; internal static async Task<Document?> TryGetCompileTimeDocumentAsync( Document designTimeDocument, Solution compileTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { var compileTimeDocument = await compileTimeSolution.GetDocumentAsync(designTimeDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (compileTimeDocument != null) { return compileTimeDocument; } if (!IsRazorDesignTimeDocument(designTimeDocument.DocumentState)) { return null; } var designTimeProjectDirectoryName = PathUtilities.GetDirectoryName(designTimeDocument.Project.FilePath)!; var generatedDocumentPath = BuildGeneratedDocumentPath(designTimeProjectDirectoryName, designTimeDocument.FilePath!, generatedDocumentPathPrefix); var generatedDocumentPathNet6Preview7 = BuildGeneratedDocumentPathNet6Preview7(designTimeProjectDirectoryName, designTimeDocument.FilePath!, generatedDocumentPathPrefix); var sourceGeneratedDocuments = await compileTimeSolution.GetRequiredProject(designTimeDocument.Project.Id).GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); return sourceGeneratedDocuments.SingleOrDefault(d => d.FilePath == generatedDocumentPath || d.FilePath == generatedDocumentPathNet6Preview7); } /// <summary> /// Prior to .net6 preview 7, the source generated path was built using a relative path with a preceding \ /// and without only .cs as part of the extension. /// </summary> private static string BuildGeneratedDocumentPath(string designTimeProjectDirectoryName, string designTimeDocumentFilePath, string? generatedDocumentPathPrefix) { var relativeDocumentPath = GetRelativeDocumentPathWithPrecedingSlash(designTimeProjectDirectoryName, designTimeDocumentFilePath); var generatedDocumentPath = GetGeneratedDocumentPathWithoutExtension(relativeDocumentPath, generatedDocumentPathPrefix) + ".cs"; return generatedDocumentPath; } /// <summary> /// In .net6 p7 the source generator changed to passing in the relative doc path without a leading \ to GetIdentifierFromPath /// which caused the source generated file name to no longer be prefixed by an _. Additionally, the file extension was changed to .g.cs /// </summary> private static string BuildGeneratedDocumentPathNet6Preview7(string designTimeProjectDirectoryName, string designTimeDocumentFilePath, string? generatedDocumentPathPrefix) { var relativeDocumentPath = GetRelativeDocumentPath(designTimeProjectDirectoryName, designTimeDocumentFilePath); var generatedDocumentPath = GetGeneratedDocumentPathWithoutExtension(relativeDocumentPath, generatedDocumentPathPrefix) + ".g.cs"; return generatedDocumentPath; } private static string GetRelativeDocumentPath(string projectDirectory, string designTimeDocumentFilePath) => PathUtilities.GetRelativePath(projectDirectory, designTimeDocumentFilePath)[..^".g.cs".Length]; private static string GetRelativeDocumentPathWithPrecedingSlash(string projectDirectory, string designTimeDocumentFilePath) => Path.Combine("\\", GetRelativeDocumentPath(projectDirectory, designTimeDocumentFilePath)); private static string GetGeneratedDocumentPathWithoutExtension(string relativeDocumentPath, string? generatedDocumentPathPrefix) => Path.Combine(generatedDocumentPathPrefix ?? s_razorSourceGeneratorFileNamePrefix, GetIdentifierFromPath(relativeDocumentPath)); private static bool HasMatchingFilePath(string designTimeDocumentFilePath, string designTimeProjectDirectory, string compileTimeFilePath) { // Check for matching file names created from a relative path with and without a preceding slash as both // are valid depening on the which sdk. See BuildGeneratedDocumentPathNet6Preview7. var relativeDocumentPath = GetRelativeDocumentPath(designTimeProjectDirectory, designTimeDocumentFilePath); var relativeDocumentPathWithSlash = GetRelativeDocumentPathWithPrecedingSlash(designTimeProjectDirectory, designTimeDocumentFilePath); var compileTimeFileName = PathUtilities.GetFileName(compileTimeFilePath, includeExtension: false); // Sdks including and after .net6 preview7 have compile time file names ending with ".g.cs". if (compileTimeFileName.EndsWith(".g")) compileTimeFileName = compileTimeFileName[..^".g".Length]; return compileTimeFileName == GetIdentifierFromPath(relativeDocumentPath) || compileTimeFileName == GetIdentifierFromPath(relativeDocumentPathWithSlash); } internal static async Task<ImmutableArray<DocumentId>> GetDesignTimeDocumentsAsync( Solution compileTimeSolution, ImmutableArray<DocumentId> compileTimeDocumentIds, Solution designTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var result); using var _2 = PooledDictionary<ProjectId, ArrayBuilder<string>>.GetInstance(out var compileTimeFilePathsByProject); generatedDocumentPathPrefix ??= s_razorSourceGeneratorFileNamePrefix; foreach (var compileTimeDocumentId in compileTimeDocumentIds) { if (designTimeSolution.ContainsDocument(compileTimeDocumentId)) { result.Add(compileTimeDocumentId); } else { var compileTimeDocument = await compileTimeSolution.GetTextDocumentAsync(compileTimeDocumentId, cancellationToken).ConfigureAwait(false); var filePath = compileTimeDocument?.State.FilePath; if (filePath?.StartsWith(generatedDocumentPathPrefix) == true) { compileTimeFilePathsByProject.MultiAdd(compileTimeDocumentId.ProjectId, filePath); } } } if (result.Count == compileTimeDocumentIds.Length) { Debug.Assert(compileTimeFilePathsByProject.Count == 0); return compileTimeDocumentIds; } foreach (var (projectId, compileTimeFilePaths) in compileTimeFilePathsByProject) { var designTimeProjectState = designTimeSolution.GetProjectState(projectId); if (designTimeProjectState == null) { continue; } var designTimeProjectDirectory = PathUtilities.GetDirectoryName(designTimeProjectState.FilePath)!; foreach (var (_, designTimeDocumentState) in designTimeProjectState.DocumentStates.States) { if (IsRazorDesignTimeDocument(designTimeDocumentState) && compileTimeFilePaths.Any(compileTimeFilePath => HasMatchingFilePath(designTimeDocumentState.FilePath!, designTimeProjectDirectory, compileTimeFilePath))) { result.Add(designTimeDocumentState.Id); } } } compileTimeFilePathsByProject.FreeValues(); return result.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Provides a compile-time view of the current workspace solution. /// Workaround for Razor projects which generate both design-time and compile-time source files. /// TODO: remove https://github.com/dotnet/roslyn/issues/51678 /// </summary> internal sealed class CompileTimeSolutionProvider : ICompileTimeSolutionProvider { [ExportWorkspaceServiceFactory(typeof(ICompileTimeSolutionProvider), WorkspaceKind.Host), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new CompileTimeSolutionProvider(workspaceServices.Workspace); } private const string RazorEncConfigFileName = "RazorSourceGenerator.razorencconfig"; private const string RazorSourceGeneratorAssemblyName = "Microsoft.NET.Sdk.Razor.SourceGenerators"; private const string RazorSourceGeneratorTypeName = "Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator"; private static readonly string s_razorSourceGeneratorFileNamePrefix = Path.Combine(RazorSourceGeneratorAssemblyName, RazorSourceGeneratorTypeName); private readonly Workspace _workspace; private readonly object _gate = new(); /// <summary> /// Cached compile time solution corresponding to the <see cref="Workspace.PrimaryBranchId"/> /// </summary> private (int DesignTimeSolutionVersion, BranchId DesignTimeSolutionBranch, Solution CompileTimeSolution)? _primaryBranchCompileTimeCache; /// <summary> /// Cached compile time solution for a forked branch. This is used primarily by LSP cases where /// we fork the workspace solution and request diagnostics for the forked solution. /// </summary> private (int DesignTimeSolutionVersion, BranchId DesignTimeSolutionBranch, Solution CompileTimeSolution)? _forkedBranchCompileTimeCache; public CompileTimeSolutionProvider(Workspace workspace) { workspace.WorkspaceChanged += (s, e) => { if (e.Kind is WorkspaceChangeKind.SolutionCleared or WorkspaceChangeKind.SolutionRemoved) { lock (_gate) { _primaryBranchCompileTimeCache = null; _forkedBranchCompileTimeCache = null; } } }; _workspace = workspace; } private static bool IsRazorAnalyzerConfig(TextDocumentState documentState) => documentState.FilePath != null && documentState.FilePath.EndsWith(RazorEncConfigFileName, StringComparison.OrdinalIgnoreCase); public Solution GetCompileTimeSolution(Solution designTimeSolution) { lock (_gate) { var cachedCompileTimeSolution = GetCachedCompileTimeSolution(designTimeSolution); // Design time solution hasn't changed since we calculated the last compile-time solution: if (cachedCompileTimeSolution != null) { return cachedCompileTimeSolution; } using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var configIdsToRemove); using var _2 = ArrayBuilder<DocumentId>.GetInstance(out var documentIdsToRemove); foreach (var (_, projectState) in designTimeSolution.State.ProjectStates) { var anyConfigs = false; foreach (var (_, configState) in projectState.AnalyzerConfigDocumentStates.States) { if (IsRazorAnalyzerConfig(configState)) { configIdsToRemove.Add(configState.Id); anyConfigs = true; } } // only remove design-time only documents when source-generated ones replace them if (anyConfigs) { foreach (var (_, documentState) in projectState.DocumentStates.States) { if (documentState.Attributes.DesignTimeOnly) { documentIdsToRemove.Add(documentState.Id); } } } } var compileTimeSolution = designTimeSolution .RemoveAnalyzerConfigDocuments(configIdsToRemove.ToImmutable()) .RemoveDocuments(documentIdsToRemove.ToImmutable()); UpdateCachedCompileTimeSolution(designTimeSolution, compileTimeSolution); return compileTimeSolution; } } private Solution? GetCachedCompileTimeSolution(Solution designTimeSolution) { // If the design time solution is for the primary branch, retrieve the last cached solution for it. // Otherwise this is a forked solution, so retrieve the last forked compile time solution we calculated. var cachedCompileTimeSolution = designTimeSolution.BranchId == _workspace.PrimaryBranchId ? _primaryBranchCompileTimeCache : _forkedBranchCompileTimeCache; // Verify that the design time solution has not changed since the last calculated compile time solution and that // the design time solution branch matches the branch of the design time solution we calculated the compile time solution for. if (cachedCompileTimeSolution != null && designTimeSolution.WorkspaceVersion == cachedCompileTimeSolution.Value.DesignTimeSolutionVersion && designTimeSolution.BranchId == cachedCompileTimeSolution.Value.DesignTimeSolutionBranch) { return cachedCompileTimeSolution.Value.CompileTimeSolution; } return null; } private void UpdateCachedCompileTimeSolution(Solution designTimeSolution, Solution compileTimeSolution) { if (designTimeSolution.BranchId == _workspace.PrimaryBranchId) { _primaryBranchCompileTimeCache = (designTimeSolution.WorkspaceVersion, designTimeSolution.BranchId, compileTimeSolution); } else { _forkedBranchCompileTimeCache = (designTimeSolution.WorkspaceVersion, designTimeSolution.BranchId, compileTimeSolution); } } // Copied from // https://github.com/dotnet/sdk/blob/main/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs#L32 private static string GetIdentifierFromPath(string filePath) { var builder = new StringBuilder(filePath.Length); for (var i = 0; i < filePath.Length; i++) { switch (filePath[i]) { case ':' or '\\' or '/': case char ch when !char.IsLetterOrDigit(ch): builder.Append('_'); break; default: builder.Append(filePath[i]); break; } } return builder.ToString(); } private static bool IsRazorDesignTimeDocument(DocumentState documentState) => documentState.Attributes.DesignTimeOnly && documentState.FilePath?.EndsWith(".razor.g.cs") == true; internal static async Task<Document?> TryGetCompileTimeDocumentAsync( Document designTimeDocument, Solution compileTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { var compileTimeDocument = await compileTimeSolution.GetDocumentAsync(designTimeDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (compileTimeDocument != null) { return compileTimeDocument; } if (!IsRazorDesignTimeDocument(designTimeDocument.DocumentState)) { return null; } var designTimeProjectDirectoryName = PathUtilities.GetDirectoryName(designTimeDocument.Project.FilePath)!; var generatedDocumentPath = BuildGeneratedDocumentPath(designTimeProjectDirectoryName, designTimeDocument.FilePath!, generatedDocumentPathPrefix); var generatedDocumentPathNet6Preview7 = BuildGeneratedDocumentPathNet6Preview7(designTimeProjectDirectoryName, designTimeDocument.FilePath!, generatedDocumentPathPrefix); var sourceGeneratedDocuments = await compileTimeSolution.GetRequiredProject(designTimeDocument.Project.Id).GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); return sourceGeneratedDocuments.SingleOrDefault(d => d.FilePath == generatedDocumentPath || d.FilePath == generatedDocumentPathNet6Preview7); } /// <summary> /// Prior to .net6 preview 7, the source generated path was built using a relative path with a preceding \ /// and without only .cs as part of the extension. /// </summary> private static string BuildGeneratedDocumentPath(string designTimeProjectDirectoryName, string designTimeDocumentFilePath, string? generatedDocumentPathPrefix) { var relativeDocumentPath = GetRelativeDocumentPathWithPrecedingSlash(designTimeProjectDirectoryName, designTimeDocumentFilePath); var generatedDocumentPath = GetGeneratedDocumentPathWithoutExtension(relativeDocumentPath, generatedDocumentPathPrefix) + ".cs"; return generatedDocumentPath; } /// <summary> /// In .net6 p7 the source generator changed to passing in the relative doc path without a leading \ to GetIdentifierFromPath /// which caused the source generated file name to no longer be prefixed by an _. Additionally, the file extension was changed to .g.cs /// </summary> private static string BuildGeneratedDocumentPathNet6Preview7(string designTimeProjectDirectoryName, string designTimeDocumentFilePath, string? generatedDocumentPathPrefix) { var relativeDocumentPath = GetRelativeDocumentPath(designTimeProjectDirectoryName, designTimeDocumentFilePath); var generatedDocumentPath = GetGeneratedDocumentPathWithoutExtension(relativeDocumentPath, generatedDocumentPathPrefix) + ".g.cs"; return generatedDocumentPath; } private static string GetRelativeDocumentPath(string projectDirectory, string designTimeDocumentFilePath) => PathUtilities.GetRelativePath(projectDirectory, designTimeDocumentFilePath)[..^".g.cs".Length]; private static string GetRelativeDocumentPathWithPrecedingSlash(string projectDirectory, string designTimeDocumentFilePath) => Path.Combine("\\", GetRelativeDocumentPath(projectDirectory, designTimeDocumentFilePath)); private static string GetGeneratedDocumentPathWithoutExtension(string relativeDocumentPath, string? generatedDocumentPathPrefix) => Path.Combine(generatedDocumentPathPrefix ?? s_razorSourceGeneratorFileNamePrefix, GetIdentifierFromPath(relativeDocumentPath)); private static bool HasMatchingFilePath(string designTimeDocumentFilePath, string designTimeProjectDirectory, string compileTimeFilePath) { // Check for matching file names created from a relative path with and without a preceding slash as both // are valid depening on the which sdk. See BuildGeneratedDocumentPathNet6Preview7. var relativeDocumentPath = GetRelativeDocumentPath(designTimeProjectDirectory, designTimeDocumentFilePath); var relativeDocumentPathWithSlash = GetRelativeDocumentPathWithPrecedingSlash(designTimeProjectDirectory, designTimeDocumentFilePath); var compileTimeFileName = PathUtilities.GetFileName(compileTimeFilePath, includeExtension: false); // Sdks including and after .net6 preview7 have compile time file names ending with ".g.cs". if (compileTimeFileName.EndsWith(".g")) compileTimeFileName = compileTimeFileName[..^".g".Length]; return compileTimeFileName == GetIdentifierFromPath(relativeDocumentPath) || compileTimeFileName == GetIdentifierFromPath(relativeDocumentPathWithSlash); } internal static async Task<ImmutableArray<DocumentId>> GetDesignTimeDocumentsAsync( Solution compileTimeSolution, ImmutableArray<DocumentId> compileTimeDocumentIds, Solution designTimeSolution, CancellationToken cancellationToken, string? generatedDocumentPathPrefix = null) { using var _1 = ArrayBuilder<DocumentId>.GetInstance(out var result); using var _2 = PooledDictionary<ProjectId, ArrayBuilder<string>>.GetInstance(out var compileTimeFilePathsByProject); generatedDocumentPathPrefix ??= s_razorSourceGeneratorFileNamePrefix; foreach (var compileTimeDocumentId in compileTimeDocumentIds) { if (designTimeSolution.ContainsDocument(compileTimeDocumentId)) { result.Add(compileTimeDocumentId); } else { var compileTimeDocument = await compileTimeSolution.GetTextDocumentAsync(compileTimeDocumentId, cancellationToken).ConfigureAwait(false); var filePath = compileTimeDocument?.State.FilePath; if (filePath?.StartsWith(generatedDocumentPathPrefix) == true) { compileTimeFilePathsByProject.MultiAdd(compileTimeDocumentId.ProjectId, filePath); } } } if (result.Count == compileTimeDocumentIds.Length) { Debug.Assert(compileTimeFilePathsByProject.Count == 0); return compileTimeDocumentIds; } foreach (var (projectId, compileTimeFilePaths) in compileTimeFilePathsByProject) { var designTimeProjectState = designTimeSolution.GetProjectState(projectId); if (designTimeProjectState == null) { continue; } var designTimeProjectDirectory = PathUtilities.GetDirectoryName(designTimeProjectState.FilePath)!; foreach (var (_, designTimeDocumentState) in designTimeProjectState.DocumentStates.States) { if (IsRazorDesignTimeDocument(designTimeDocumentState) && compileTimeFilePaths.Any(compileTimeFilePath => HasMatchingFilePath(designTimeDocumentState.FilePath!, designTimeProjectDirectory, compileTimeFilePath))) { result.Add(designTimeDocumentState.Id); } } } compileTimeFilePathsByProject.FreeValues(); return result.ToImmutable(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/Portable/FindSymbols/IFindReferencesProgress.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.FindSymbols { /// <summary> /// Reports the progress of the FindReferences operation. Note: these methods may be called on /// any thread. /// </summary> public interface IFindReferencesProgress { void OnStarted(); void OnCompleted(); void OnFindInDocumentStarted(Document document); void OnFindInDocumentCompleted(Document document); void OnDefinitionFound(ISymbol symbol); void OnReferenceFound(ISymbol symbol, ReferenceLocation location); void ReportProgress(int current, int maximum); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.FindSymbols { /// <summary> /// Reports the progress of the FindReferences operation. Note: these methods may be called on /// any thread. /// </summary> public interface IFindReferencesProgress { void OnStarted(); void OnCompleted(); void OnFindInDocumentStarted(Document document); void OnFindInDocumentCompleted(Document document); void OnDefinitionFound(ISymbol symbol); void OnReferenceFound(ISymbol symbol, ReferenceLocation location); void ReportProgress(int current, int maximum); } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/Core/Portable/InternalLanguageNames.cs
// Licensed to the .NET Foundation under one or more 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 provides constants for internal partner language names. /// </summary> internal static class InternalLanguageNames { public const string TypeScript = "TypeScript"; } }
// Licensed to the .NET Foundation under one or more 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 provides constants for internal partner language names. /// </summary> internal static class InternalLanguageNames { public const string TypeScript = "TypeScript"; } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./.git/hooks/pre-receive.sample
#!/bin/sh # # An example hook script to make use of push options. # The example simply echoes all push options that start with 'echoback=' # and rejects all pushes when the "reject" push option is used. # # To enable this hook, rename this file to "pre-receive". if test -n "$GIT_PUSH_OPTION_COUNT" then i=0 while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" do eval "value=\$GIT_PUSH_OPTION_$i" case "$value" in echoback=*) echo "echo from the pre-receive-hook: ${value#*=}" >&2 ;; reject) exit 1 esac i=$((i + 1)) done fi
#!/bin/sh # # An example hook script to make use of push options. # The example simply echoes all push options that start with 'echoback=' # and rejects all pushes when the "reject" push option is used. # # To enable this hook, rename this file to "pre-receive". if test -n "$GIT_PUSH_OPTION_COUNT" then i=0 while test "$i" -lt "$GIT_PUSH_OPTION_COUNT" do eval "value=\$GIT_PUSH_OPTION_$i" case "$value" in echoback=*) echo "echo from the pre-receive-hook: ${value#*=}" >&2 ;; reject) exit 1 esac i=$((i + 1)) done fi
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { // Workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1162267 internal interface IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { Workspace RemoteLanguageServiceWorkspace { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { // Workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1162267 internal interface IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { Workspace RemoteLanguageServiceWorkspace { get; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ChecksumKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ChecksumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ChecksumKeywordRecommender() : base(SyntaxKind.ChecksumKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // # pragma | // # pragma w| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.PragmaKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ChecksumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ChecksumKeywordRecommender() : base(SyntaxKind.ChecksumKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // # pragma | // # pragma w| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.PragmaKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.ModifiedComplexTrivia.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class ModifiedComplexTrivia : TriviaDataWithList { private readonly ComplexTrivia _original; public ModifiedComplexTrivia(AnalyzerConfigOptions options, ComplexTrivia original, int lineBreaks, int space) : base(options, original.Token1.Language) { Contract.ThrowIfNull(original); _original = original; // linebreak and space can become negative during formatting. but it should be normalized to >= 0 // at the end. this.LineBreaks = lineBreaks; this.Spaces = space; } public override bool ContainsChanges { get { return false; } } public override bool TreatAsElastic { get { return _original.TreatAsElastic; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => _original.WithSpace(space, context, formattingRules); public override TriviaData WithLine( int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { return _original.WithLine(line, indentation, context, formattingRules, cancellationToken); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { return _original.WithIndentation(indentation, context, formattingRules, cancellationToken); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { Contract.ThrowIfFalse(this.SecondTokenIsFirstTokenOnLine); var token1 = _original.Token1; var token2 = _original.Token2; var triviaList = new TriviaList(token1.TrailingTrivia, token2.LeadingTrivia); Contract.ThrowIfFalse(triviaList.Count > 0); // okay, now, check whether we need or are able to format noisy tokens if (CodeShapeAnalyzer.ContainsSkippedTokensOrText(triviaList)) { return; } formattingResultApplier(tokenPairIndex, context.TokenStream, new FormattedComplexTrivia( context, formattingRules, _original.Token1, _original.Token2, this.LineBreaks, this.Spaces, _original.OriginalString, cancellationToken)); } public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => throw new NotImplementedException(); public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class ModifiedComplexTrivia : TriviaDataWithList { private readonly ComplexTrivia _original; public ModifiedComplexTrivia(AnalyzerConfigOptions options, ComplexTrivia original, int lineBreaks, int space) : base(options, original.Token1.Language) { Contract.ThrowIfNull(original); _original = original; // linebreak and space can become negative during formatting. but it should be normalized to >= 0 // at the end. this.LineBreaks = lineBreaks; this.Spaces = space; } public override bool ContainsChanges { get { return false; } } public override bool TreatAsElastic { get { return _original.TreatAsElastic; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => _original.WithSpace(space, context, formattingRules); public override TriviaData WithLine( int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { return _original.WithLine(line, indentation, context, formattingRules, cancellationToken); } public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { return _original.WithIndentation(indentation, context, formattingRules, cancellationToken); } public override void Format( FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { Contract.ThrowIfFalse(this.SecondTokenIsFirstTokenOnLine); var token1 = _original.Token1; var token2 = _original.Token2; var triviaList = new TriviaList(token1.TrailingTrivia, token2.LeadingTrivia); Contract.ThrowIfFalse(triviaList.Count > 0); // okay, now, check whether we need or are able to format noisy tokens if (CodeShapeAnalyzer.ContainsSkippedTokensOrText(triviaList)) { return; } formattingResultApplier(tokenPairIndex, context.TokenStream, new FormattedComplexTrivia( context, formattingRules, _original.Token1, _original.Token2, this.LineBreaks, this.Spaces, _original.OriginalString, cancellationToken)); } public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => throw new NotImplementedException(); public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_NavigationKeys.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); 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; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal bool TryHandleUpKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectPreviousItem()); } internal bool TryHandleDownKey() { AssertIsForeground(); return ChangeSelection(() => sessionOpt.PresenterSession.SelectNextItem()); } private bool ChangeSelection(Action computationAction) { AssertIsForeground(); if (!IsSessionActive) { // No computation running, so just let the editor handle this. return false; } // If we haven't started our editor session yet, just abort. // The user hasn't seen a SigHelp presentation yet, so they're // probably not trying to change the currently visible overload. if (!sessionOpt.PresenterSession.EditorSessionIsActive) { DismissSessionIfActive(); return false; } // If we've finished computing the items then use the navigation commands to change the // selected item. Otherwise, the user was just typing and is now moving through the // file. In this case stop everything we're doing. var model = sessionOpt.InitialUnfilteredModel != null ? WaitForController() : null; // Check if completion is still active. Then update the computation appropriately. // // Also, if we only computed one item, then the user doesn't want to select anything // else. Just stop and let the editor handle the nav character. if (model != null && model.Items.Count > 1) { computationAction(); return true; } else { // Dismiss ourselves and actually allow the editor to navigate. DismissSessionIfActive(); return false; } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Analyzers/CSharp/CodeFixes/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertSwitchStatementToExpression), Shared] internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertSwitchStatementToExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var switchLocation = context.Diagnostics.First().AdditionalLocations[0]; var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, context.CancellationToken); if (switchStatement.ContainsDirectives) { // Avoid providing code fixes for switch statements containing directives return Task.CompletedTask; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var spansDisposer = ArrayBuilder<TextSpan>.GetInstance(diagnostics.Length, out var spans); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); var switchLocation = diagnostic.AdditionalLocations[0]; if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan)) { // Skip nested switch expressions in case of a fix-all operation. continue; } spans.Add(switchLocation.SourceSpan); var properties = diagnostic.Properties; var nodeToGenerate = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]); var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]); var declaratorToRemoveLocationOpt = diagnostic.AdditionalLocations.ElementAtOrDefault(1); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SyntaxNode declaratorToRemoveNodeOpt = null; ITypeSymbol declaratorToRemoveTypeOpt = null; if (declaratorToRemoveLocationOpt != null) { declaratorToRemoveNodeOpt = declaratorToRemoveLocationOpt.FindNode(cancellationToken); declaratorToRemoveTypeOpt = semanticModel.GetDeclaredSymbol(declaratorToRemoveNodeOpt, cancellationToken).GetSymbolType(); } var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); var switchExpression = Rewriter.Rewrite( switchStatement, semanticModel, declaratorToRemoveTypeOpt, nodeToGenerate, shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement, generateDeclaration: declaratorToRemoveLocationOpt is object); editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation)); if (declaratorToRemoveLocationOpt is object) { editor.RemoveNode(declaratorToRemoveLocationOpt.FindNode(cancellationToken)); } if (shouldRemoveNextStatement) { // Already morphed into the top-level switch expression. SyntaxNode nextStatement = switchStatement.GetNextStatement(); Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)); editor.RemoveNode(nextStatement.IsParentKind(SyntaxKind.GlobalStatement) ? nextStatement.Parent : nextStatement); } } } private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Convert_switch_statement_to_expression, createChangedDocument, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertSwitchStatementToExpression), Shared] internal sealed partial class ConvertSwitchStatementToExpressionCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertSwitchStatementToExpressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var switchLocation = context.Diagnostics.First().AdditionalLocations[0]; var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, context.CancellationToken); if (switchStatement.ContainsDirectives) { // Avoid providing code fixes for switch statements containing directives return Task.CompletedTask; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { using var spansDisposer = ArrayBuilder<TextSpan>.GetInstance(diagnostics.Length, out var spans); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); var switchLocation = diagnostic.AdditionalLocations[0]; if (spans.Any((s, nodeSpan) => s.Contains(nodeSpan), switchLocation.SourceSpan)) { // Skip nested switch expressions in case of a fix-all operation. continue; } spans.Add(switchLocation.SourceSpan); var properties = diagnostic.Properties; var nodeToGenerate = (SyntaxKind)int.Parse(properties[Constants.NodeToGenerateKey]); var shouldRemoveNextStatement = bool.Parse(properties[Constants.ShouldRemoveNextStatementKey]); var declaratorToRemoveLocationOpt = diagnostic.AdditionalLocations.ElementAtOrDefault(1); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); SyntaxNode declaratorToRemoveNodeOpt = null; ITypeSymbol declaratorToRemoveTypeOpt = null; if (declaratorToRemoveLocationOpt != null) { declaratorToRemoveNodeOpt = declaratorToRemoveLocationOpt.FindNode(cancellationToken); declaratorToRemoveTypeOpt = semanticModel.GetDeclaredSymbol(declaratorToRemoveNodeOpt, cancellationToken).GetSymbolType(); } var switchStatement = (SwitchStatementSyntax)switchLocation.FindNode(getInnermostNodeForTie: true, cancellationToken); var switchExpression = Rewriter.Rewrite( switchStatement, semanticModel, declaratorToRemoveTypeOpt, nodeToGenerate, shouldMoveNextStatementToSwitchExpression: shouldRemoveNextStatement, generateDeclaration: declaratorToRemoveLocationOpt is object); editor.ReplaceNode(switchStatement, switchExpression.WithAdditionalAnnotations(Formatter.Annotation)); if (declaratorToRemoveLocationOpt is object) { editor.RemoveNode(declaratorToRemoveLocationOpt.FindNode(cancellationToken)); } if (shouldRemoveNextStatement) { // Already morphed into the top-level switch expression. SyntaxNode nextStatement = switchStatement.GetNextStatement(); Debug.Assert(nextStatement.IsKind(SyntaxKind.ThrowStatement, SyntaxKind.ReturnStatement)); editor.RemoveNode(nextStatement.IsParentKind(SyntaxKind.GlobalStatement) ? nextStatement.Parent : nextStatement); } } } private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Convert_switch_statement_to_expression, createChangedDocument, nameof(CSharpAnalyzersResources.Convert_switch_statement_to_expression)) { } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/CSharpTest/ReverseForStatement/ReverseForStatementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ReverseForStatement; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReverseForStatement { public class ReverseForStatementTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpReverseForStatementCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutInitializer() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutCondition() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; ; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutIncrementor() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; ) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableReferencedInCondition() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; j < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableReferencedInIncrementor() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; j++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableInitializer() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithMismatchedConditionAndIncrementor1() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithMismatchedConditionAndIncrementor2() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i >= args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrement1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementConstants1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < 10; i++) { } } }", @"class C { void M(string[] args) { for (int i = 10 - 1; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrementConstants1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 10 - 1; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i < 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestIncrementPreIncrement() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; ++i) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; --i) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestIncrementAddAssignment() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i += 1) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; i -= 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithNonOneIncrementValue() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i += 2) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrement() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = args.Length - 1; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementEquals1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i <= args.Length; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrementEquals() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = args.Length; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i <= args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (/*t1*/int/*t2*/i/*t3*/=/*t4*/0/*t5*/;/*t6*/i/*t7*/</*t8*/args.Length/*t9*/;/*t10*/i/*t11*/++/*t12*/) { } } }", @"class C { void M(string[] args) { for (/*t1*/int/*t2*/i/*t3*/=/*t4*/args.Length/*t9*/- 1;/*t6*/i/*t7*/>=/*t8*/0/*t5*/;/*t10*/i/*t11*/--/*t12*/) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementSwappedConditions() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; args.Length > i; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; 0 <= i; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementEqualsSwappedConditions() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; args.Length >= i; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length; 0 <= i; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteOneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (byte i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (byte i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (ushort i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (ushort i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (uint i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (uint i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (ulong i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (ulong i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ushort i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (uint i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ulong i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteMax() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte x = byte.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ushort x = ushort.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (uint x = uint.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ulong x = ulong.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteZeroMinReverse() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte i = 10; i >= 0; i--) { } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ReverseForStatement; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReverseForStatement { public class ReverseForStatementTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpReverseForStatementCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutInitializer() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutCondition() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; ; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutIncrementor() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; ) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableReferencedInCondition() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; j < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableReferencedInIncrementor() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; j++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithoutVariableInitializer() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithMismatchedConditionAndIncrementor1() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithMismatchedConditionAndIncrementor2() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i >= args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrement1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementConstants1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < 10; i++) { } } }", @"class C { void M(string[] args) { for (int i = 10 - 1; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrementConstants1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 10 - 1; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i < 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestIncrementPreIncrement() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; ++i) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; --i) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestIncrementAddAssignment() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i += 1) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; i >= 0; i -= 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWithNonOneIncrementValue() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i < args.Length; i += 2) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrement() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = args.Length - 1; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i < args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementEquals1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; i <= args.Length; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length; i >= 0; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostDecrementEquals() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = args.Length; i >= 0; i--) { } } }", @"class C { void M(string[] args) { for (int i = 0; i <= args.Length; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (/*t1*/int/*t2*/i/*t3*/=/*t4*/0/*t5*/;/*t6*/i/*t7*/</*t8*/args.Length/*t9*/;/*t10*/i/*t11*/++/*t12*/) { } } }", @"class C { void M(string[] args) { for (/*t1*/int/*t2*/i/*t3*/=/*t4*/args.Length/*t9*/- 1;/*t6*/i/*t7*/>=/*t8*/0/*t5*/;/*t10*/i/*t11*/--/*t12*/) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementSwappedConditions() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; args.Length > i; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length - 1; 0 <= i; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestPostIncrementEqualsSwappedConditions() { await TestInRegularAndScriptAsync( @"class C { void M(string[] args) { [||]for (int i = 0; args.Length >= i; i++) { } } }", @"class C { void M(string[] args) { for (int i = args.Length; 0 <= i; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteOneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (byte i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (byte i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (ushort i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (ushort i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (uint i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (uint i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64OneMin() { await TestInRegularAndScript1Async( @"class C { void M(string[] args) { [||]for (ulong i = 1; i <= 10; i++) { } } }", @"class C { void M(string[] args) { for (ulong i = 10; i >= 1; i--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ushort i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (uint i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64ZeroMin() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ulong i = 0; i <= 10; i++) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteMax() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte x = byte.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt16Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ushort x = ushort.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt32Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (uint x = uint.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestUInt64Max() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (ulong x = ulong.MaxValue; x >= 10; x--) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestByteZeroMinReverse() { await TestMissingAsync( @"class C { void M(string[] args) { [||]for (byte i = 10; i >= 0; i--) { } } }"); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/EventMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.ErrorReporting; namespace Roslyn.Utilities { internal class EventMap { private readonly NonReentrantLock _guard = new(); private readonly Dictionary<string, object> _eventNameToRegistries = new(); public EventMap() { } public void AddEventHandler<TEventHandler>(string eventName, TEventHandler eventHandler) where TEventHandler : class { using (_guard.DisposableWait()) { var registries = GetRegistries_NoLock<TEventHandler>(eventName); var newRegistries = registries.Add(new Registry<TEventHandler>(eventHandler)); SetRegistries_NoLock(eventName, newRegistries); } } public void RemoveEventHandler<TEventHandler>(string eventName, TEventHandler eventHandler) where TEventHandler : class { using (_guard.DisposableWait()) { var registries = GetRegistries_NoLock<TEventHandler>(eventName); // remove disabled registrations from list var newRegistries = registries.RemoveAll(r => r.HasHandler(eventHandler)); if (newRegistries != registries) { // disable all registrations of this handler (so pending raise events can be squelched) // This does not guarantee no race condition between Raise and Remove but greatly reduces it. foreach (var registry in registries.Where(r => r.HasHandler(eventHandler))) { registry.Unregister(); } SetRegistries_NoLock(eventName, newRegistries); } } } [PerformanceSensitive( "https://developercommunity.visualstudio.com/content/problem/854696/changing-target-framework-takes-10-minutes-with-10.html", AllowImplicitBoxing = false)] public EventHandlerSet<TEventHandler> GetEventHandlers<TEventHandler>(string eventName) where TEventHandler : class { return new EventHandlerSet<TEventHandler>(this.GetRegistries<TEventHandler>(eventName)); } private ImmutableArray<Registry<TEventHandler>> GetRegistries<TEventHandler>(string eventName) where TEventHandler : class { using (_guard.DisposableWait()) { return GetRegistries_NoLock<TEventHandler>(eventName); } } private ImmutableArray<Registry<TEventHandler>> GetRegistries_NoLock<TEventHandler>(string eventName) where TEventHandler : class { _guard.AssertHasLock(); if (_eventNameToRegistries.TryGetValue(eventName, out var registries)) { return (ImmutableArray<Registry<TEventHandler>>)registries; } return ImmutableArray.Create<Registry<TEventHandler>>(); } private void SetRegistries_NoLock<TEventHandler>(string eventName, ImmutableArray<Registry<TEventHandler>> registries) where TEventHandler : class { _guard.AssertHasLock(); _eventNameToRegistries[eventName] = registries; } internal class Registry<TEventHandler> : IEquatable<Registry<TEventHandler>?> where TEventHandler : class { private TEventHandler? _handler; public Registry(TEventHandler handler) => _handler = handler; public void Unregister() => _handler = null; public void Invoke(Action<TEventHandler> invoker) { var handler = _handler; if (handler != null) { invoker(handler); } } public bool HasHandler(TEventHandler handler) => handler.Equals(_handler); public bool Equals(Registry<TEventHandler>? other) { if (other == null) { return false; } if (other._handler == null && _handler == null) { return true; } if (other._handler == null || _handler == null) { return false; } return other._handler.Equals(_handler); } public override bool Equals(object? obj) => Equals(obj as Registry<TEventHandler>); public override int GetHashCode() => _handler == null ? 0 : _handler.GetHashCode(); } internal struct EventHandlerSet<TEventHandler> where TEventHandler : class { private ImmutableArray<Registry<TEventHandler>> _registries; internal EventHandlerSet(ImmutableArray<Registry<TEventHandler>> registries) => _registries = registries; public bool HasHandlers { get { return _registries != null && _registries.Length > 0; } } public void RaiseEvent(Action<TEventHandler> invoker) { // The try/catch here is to find additional telemetry for https://devdiv.visualstudio.com/DevDiv/_queries/query/71ee8553-7220-4b2a-98cf-20edab701fd1/. // We've realized there's a problem with our eventing, where if an exception is encountered while calling into subscribers to Workspace events, // we won't notify all of the callers. The expectation is such an exception would be thrown to the SafeStartNew in the workspace's event queue that // will raise that as a fatal exception, but OperationCancelledExceptions might be able to propagate through and fault the task we are using in the // chain. I'm choosing to use ReportWithoutCrashAndPropagate, because if our theory here is correct, it seems the first exception isn't actually // causing crashes, and so if it turns out this is a very common situation I don't want to make a often-benign situation fatal. try { if (this.HasHandlers) { foreach (var registry in _registries) { registry.Invoke(invoker); } } } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.ErrorReporting; namespace Roslyn.Utilities { internal class EventMap { private readonly NonReentrantLock _guard = new(); private readonly Dictionary<string, object> _eventNameToRegistries = new(); public EventMap() { } public void AddEventHandler<TEventHandler>(string eventName, TEventHandler eventHandler) where TEventHandler : class { using (_guard.DisposableWait()) { var registries = GetRegistries_NoLock<TEventHandler>(eventName); var newRegistries = registries.Add(new Registry<TEventHandler>(eventHandler)); SetRegistries_NoLock(eventName, newRegistries); } } public void RemoveEventHandler<TEventHandler>(string eventName, TEventHandler eventHandler) where TEventHandler : class { using (_guard.DisposableWait()) { var registries = GetRegistries_NoLock<TEventHandler>(eventName); // remove disabled registrations from list var newRegistries = registries.RemoveAll(r => r.HasHandler(eventHandler)); if (newRegistries != registries) { // disable all registrations of this handler (so pending raise events can be squelched) // This does not guarantee no race condition between Raise and Remove but greatly reduces it. foreach (var registry in registries.Where(r => r.HasHandler(eventHandler))) { registry.Unregister(); } SetRegistries_NoLock(eventName, newRegistries); } } } [PerformanceSensitive( "https://developercommunity.visualstudio.com/content/problem/854696/changing-target-framework-takes-10-minutes-with-10.html", AllowImplicitBoxing = false)] public EventHandlerSet<TEventHandler> GetEventHandlers<TEventHandler>(string eventName) where TEventHandler : class { return new EventHandlerSet<TEventHandler>(this.GetRegistries<TEventHandler>(eventName)); } private ImmutableArray<Registry<TEventHandler>> GetRegistries<TEventHandler>(string eventName) where TEventHandler : class { using (_guard.DisposableWait()) { return GetRegistries_NoLock<TEventHandler>(eventName); } } private ImmutableArray<Registry<TEventHandler>> GetRegistries_NoLock<TEventHandler>(string eventName) where TEventHandler : class { _guard.AssertHasLock(); if (_eventNameToRegistries.TryGetValue(eventName, out var registries)) { return (ImmutableArray<Registry<TEventHandler>>)registries; } return ImmutableArray.Create<Registry<TEventHandler>>(); } private void SetRegistries_NoLock<TEventHandler>(string eventName, ImmutableArray<Registry<TEventHandler>> registries) where TEventHandler : class { _guard.AssertHasLock(); _eventNameToRegistries[eventName] = registries; } internal class Registry<TEventHandler> : IEquatable<Registry<TEventHandler>?> where TEventHandler : class { private TEventHandler? _handler; public Registry(TEventHandler handler) => _handler = handler; public void Unregister() => _handler = null; public void Invoke(Action<TEventHandler> invoker) { var handler = _handler; if (handler != null) { invoker(handler); } } public bool HasHandler(TEventHandler handler) => handler.Equals(_handler); public bool Equals(Registry<TEventHandler>? other) { if (other == null) { return false; } if (other._handler == null && _handler == null) { return true; } if (other._handler == null || _handler == null) { return false; } return other._handler.Equals(_handler); } public override bool Equals(object? obj) => Equals(obj as Registry<TEventHandler>); public override int GetHashCode() => _handler == null ? 0 : _handler.GetHashCode(); } internal struct EventHandlerSet<TEventHandler> where TEventHandler : class { private ImmutableArray<Registry<TEventHandler>> _registries; internal EventHandlerSet(ImmutableArray<Registry<TEventHandler>> registries) => _registries = registries; public bool HasHandlers { get { return _registries != null && _registries.Length > 0; } } public void RaiseEvent(Action<TEventHandler> invoker) { // The try/catch here is to find additional telemetry for https://devdiv.visualstudio.com/DevDiv/_queries/query/71ee8553-7220-4b2a-98cf-20edab701fd1/. // We've realized there's a problem with our eventing, where if an exception is encountered while calling into subscribers to Workspace events, // we won't notify all of the callers. The expectation is such an exception would be thrown to the SafeStartNew in the workspace's event queue that // will raise that as a fatal exception, but OperationCancelledExceptions might be able to propagate through and fault the task we are using in the // chain. I'm choosing to use ReportWithoutCrashAndPropagate, because if our theory here is correct, it seems the first exception isn't actually // causing crashes, and so if it turns out this is a very common situation I don't want to make a often-benign situation fatal. try { if (this.HasHandlers) { foreach (var registry in _registries) { registry.Invoke(invoker); } } } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/Core/Impl/Options/Converters/MarginConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Data; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters { public class MarginConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) => new Thickness(System.Convert.ToDouble(value), 0, 0, 0); public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) => throw new NotSupportedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Data; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Converters { public class MarginConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) => new Thickness(System.Convert.ToDouble(value), 0, 0, 0); public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) => throw new NotSupportedException(); } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Core/Implementation/BraceMatching/AbstractBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal abstract class AbstractBraceMatcher : IBraceMatcher { private readonly BraceCharacterAndKind _openBrace; private readonly BraceCharacterAndKind _closeBrace; protected AbstractBraceMatcher( BraceCharacterAndKind openBrace, BraceCharacterAndKind closeBrace) { _openBrace = openBrace; _closeBrace = closeBrace; } private bool TryFindMatchingToken(SyntaxToken token, out SyntaxToken match) { var parent = token.Parent; var braceTokens = (from child in parent.ChildNodesAndTokens() where child.IsToken let tok = child.AsToken() where tok.RawKind == _openBrace.Kind || tok.RawKind == _closeBrace.Kind where tok.Span.Length > 0 select tok).ToList(); if (braceTokens.Count == 2 && braceTokens[0].RawKind == _openBrace.Kind && braceTokens[1].RawKind == _closeBrace.Kind) { if (braceTokens[0] == token) { match = braceTokens[1]; return true; } else if (braceTokens[1] == token) { match = braceTokens[0]; return true; } } match = default; return false; } public async Task<BraceMatchingResult?> FindBracesAsync( Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (position < text.Length && this.IsBrace(text[position])) { if (token.RawKind == _openBrace.Kind && AllowedForToken(token)) { var leftToken = token; if (TryFindMatchingToken(leftToken, out var rightToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } else if (token.RawKind == _closeBrace.Kind && AllowedForToken(token)) { var rightToken = token; if (TryFindMatchingToken(rightToken, out var leftToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } } return null; } protected virtual bool AllowedForToken(SyntaxToken token) => true; private bool IsBrace(char c) => _openBrace.Character == c || _closeBrace.Character == c; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal abstract class AbstractBraceMatcher : IBraceMatcher { private readonly BraceCharacterAndKind _openBrace; private readonly BraceCharacterAndKind _closeBrace; protected AbstractBraceMatcher( BraceCharacterAndKind openBrace, BraceCharacterAndKind closeBrace) { _openBrace = openBrace; _closeBrace = closeBrace; } private bool TryFindMatchingToken(SyntaxToken token, out SyntaxToken match) { var parent = token.Parent; var braceTokens = (from child in parent.ChildNodesAndTokens() where child.IsToken let tok = child.AsToken() where tok.RawKind == _openBrace.Kind || tok.RawKind == _closeBrace.Kind where tok.Span.Length > 0 select tok).ToList(); if (braceTokens.Count == 2 && braceTokens[0].RawKind == _openBrace.Kind && braceTokens[1].RawKind == _closeBrace.Kind) { if (braceTokens[0] == token) { match = braceTokens[1]; return true; } else if (braceTokens[1] == token) { match = braceTokens[0]; return true; } } match = default; return false; } public async Task<BraceMatchingResult?> FindBracesAsync( Document document, int position, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (position < text.Length && this.IsBrace(text[position])) { if (token.RawKind == _openBrace.Kind && AllowedForToken(token)) { var leftToken = token; if (TryFindMatchingToken(leftToken, out var rightToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } else if (token.RawKind == _closeBrace.Kind && AllowedForToken(token)) { var rightToken = token; if (TryFindMatchingToken(rightToken, out var leftToken)) { return new BraceMatchingResult(leftToken.Span, rightToken.Span); } } } return null; } protected virtual bool AllowedForToken(SyntaxToken token) => true; private bool IsBrace(char c) => _openBrace.Character == c || _closeBrace.Character == c; } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodeFunctionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodeFunctionTests Inherits AbstractCodeFunctionTests #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> Class C Sub $$Goo(string s) End Sub End Class </Code> TestFullName(code, "C.Goo") End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> Class C Sub $$Goo(string s) End Sub End Class </Code> TestName(code, "Goo") End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class ExternalCodeFunctionTests Inherits AbstractCodeFunctionTests #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> Class C Sub $$Goo(string s) End Sub End Class </Code> TestFullName(code, "C.Goo") End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> Class C Sub $$Goo(string s) End Sub End Class </Code> TestName(code, "Goo") End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/Portable/Symbols/ISymbolExtensions_PerformIVTCheck.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { public static partial class ISymbolExtensions { /// <summary> /// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess, /// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the /// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`. /// </summary> internal static IVTConclusion PerformIVTCheck( this AssemblyIdentity assemblyGrantingAccessIdentity, ImmutableArray<byte> assemblyWantingAccessKey, ImmutableArray<byte> grantedToPublicKey) { // This gets a bit complicated. Let's break it down. // // First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this" // assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition // to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors: // // q1) Is GrantingAssembly strong-named? // q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name? // q3) Is WantingAssembly strong-named? // q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name? // // Before we dive into the details, we should mention two additional facts: // // * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also. // Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article // http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx // for an explanation of why this feature is desirable. // // Now, just because the compiler enforces this rule does not mean that we will never run into // a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies // were compiled with a Roslyn compiler. We still need to deal sensibly with this situation. // We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named // WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly. // // Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces // the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling // a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend. // // * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where // strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler // we do not give an error about this until emit time. In Roslyn we have a new error, CS7029, // which we give before emit time when we detect that weak-named GrantingAssembly has given friend access // to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend // access to WantingAssembly for the purposes of semantic analysis. // // Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly // references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722 // // Let's make a chart that illustrates all the possible answers to these four questions, and // what the resulting accessibility should be: // // case q1 q2 q3 q4 Result Explanation // 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend. // 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend. // // (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this. // // This method never returns NoRelationshipClaimed because if control got here, then we assume // (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow. bool q1 = assemblyGrantingAccessIdentity.IsStrongName; bool q2 = !grantedToPublicKey.IsDefaultOrEmpty; bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty; bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey); // Cases 2, 3, 7 and 8: if (q2 && !q4) { return IVTConclusion.PublicKeyDoesntMatch; } // Cases 6 and 9: if (!q1 && q3) { return IVTConclusion.OneSignedOneNot; } // Cases 1, 4, 5 and 10: return IVTConclusion.Match; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { public static partial class ISymbolExtensions { /// <summary> /// Given that an assembly with identity assemblyGrantingAccessIdentity granted access to assemblyWantingAccess, /// check the public keys to ensure the internals-visible-to check should succeed. This is used by both the /// C# and VB implementations as a helper to implement `bool IAssemblySymbol.GivesAccessTo(IAssemblySymbol toAssembly)`. /// </summary> internal static IVTConclusion PerformIVTCheck( this AssemblyIdentity assemblyGrantingAccessIdentity, ImmutableArray<byte> assemblyWantingAccessKey, ImmutableArray<byte> grantedToPublicKey) { // This gets a bit complicated. Let's break it down. // // First off, let's assume that the "other" assembly is GrantingAssembly.DLL, that the "this" // assembly is "WantingAssembly.DLL", and that GrantingAssembly has named WantingAssembly as a friend (that is a precondition // to calling this method). Whether we allow WantingAssembly to see internals of GrantingAssembly depends on these four factors: // // q1) Is GrantingAssembly strong-named? // q2) Did GrantingAssembly name WantingAssembly as a friend via a strong name? // q3) Is WantingAssembly strong-named? // q4) Does GrantingAssembly give a strong-name for WantingAssembly that matches our strong name? // // Before we dive into the details, we should mention two additional facts: // // * If the answer to q1 is "yes", and GrantingAssembly was compiled by a Roslyn compiler, then q2 must be "yes" also. // Strong-named GrantingAssembly must only be friends with strong-named WantingAssembly. See the blog article // http://blogs.msdn.com/b/ericlippert/archive/2009/06/04/alas-smith-and-jones.aspx // for an explanation of why this feature is desirable. // // Now, just because the compiler enforces this rule does not mean that we will never run into // a scenario where GrantingAssembly is strong-named and names WantingAssembly via a weak name. Not all assemblies // were compiled with a Roslyn compiler. We still need to deal sensibly with this situation. // We do so by ignoring the problem; if strong-named GrantingAssembly extends friendship to weak-named // WantingAssembly then we're done; any assembly named WantingAssembly is a friend of GrantingAssembly. // // Incidentally, the C# compiler produces error CS1726, ERR_FriendAssemblySNReq, and VB produces // the error VB31535, ERR_FriendAssemblyStrongNameRequired, when compiling // a strong-named GrantingAssembly that names a weak-named WantingAssembly as its friend. // // * If the answer to q1 is "no" and the answer to q3 is "yes" then we are in a situation where // strong-named WantingAssembly is referencing weak-named GrantingAssembly, which is illegal. In the dev10 compiler // we do not give an error about this until emit time. In Roslyn we have a new error, CS7029, // which we give before emit time when we detect that weak-named GrantingAssembly has given friend access // to strong-named WantingAssembly, which then references GrantingAssembly. However, we still want to give friend // access to WantingAssembly for the purposes of semantic analysis. // // Roslyn C# does not yet give an error in other circumstances whereby a strong-named assembly // references a weak-named assembly. See https://github.com/dotnet/roslyn/issues/26722 // // Let's make a chart that illustrates all the possible answers to these four questions, and // what the resulting accessibility should be: // // case q1 q2 q3 q4 Result Explanation // 1 YES YES YES YES SUCCESS GrantingAssembly has named this strong-named WantingAssembly as a friend. // 2 YES YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 3 YES YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 4 YES NO YES NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 5 YES NO NO NO SUCCESS GrantingAssembly has improperly (*) named any WantingAssembly as its friend. But we honor its offer of friendship. // 6 NO YES YES YES SUCCESS, BAD REF GrantingAssembly has named this strong-named WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 7 NO YES YES NO NO MATCH GrantingAssembly has named a different strong-named WantingAssembly as a friend. // 8 NO YES NO NO NO MATCH GrantingAssembly has named a strong-named WantingAssembly as a friend, but this WantingAssembly is weak-named. // 9 NO NO YES NO SUCCESS, BAD REF GrantingAssembly has named any WantingAssembly as a friend, but WantingAssembly should not be referring to a weak-named GrantingAssembly. // 10 NO NO NO NO SUCCESS GrantingAssembly has named any WantingAssembly as its friend. // // (*) GrantingAssembly was not built with a Roslyn compiler, which would have prevented this. // // This method never returns NoRelationshipClaimed because if control got here, then we assume // (as a precondition) that GrantingAssembly named WantingAssembly as a friend somehow. bool q1 = assemblyGrantingAccessIdentity.IsStrongName; bool q2 = !grantedToPublicKey.IsDefaultOrEmpty; bool q3 = !assemblyWantingAccessKey.IsDefaultOrEmpty; bool q4 = (q2 & q3) && ByteSequenceComparer.Equals(grantedToPublicKey, assemblyWantingAccessKey); // Cases 2, 3, 7 and 8: if (q2 && !q4) { return IVTConclusion.PublicKeyDoesntMatch; } // Cases 6 and 9: if (!q1 && q3) { return IVTConclusion.OneSignedOneNot; } // Cases 1, 4, 5 and 10: return IVTConclusion.Match; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/CSharpTest/GenerateOverrides/GenerateOverridesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateOverrides; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateOverrides { public class GenerateOverridesTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateOverridesCodeRefactoringProvider((IPickMembersService)parameters.fixProviderData); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task Test1() { await TestWithPickMembersDialogAsync( @" class C { [||] }", @" class C { public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } }", new[] { "Equals", "GetHashCode", "ToString" }); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestAtEndOfFile() { await TestWithPickMembersDialogAsync( @" class C[||]", @" class C { public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } } ", new[] { "Equals", "GetHashCode", "ToString" }); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestOnRecordWithSemiColon() { await TestWithPickMembersDialogAsync(@" record C[||]; ", @" record C { public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } } ", new[] { "GetHashCode", "ToString" }); } [WorkItem(17698, "https://github.com/dotnet/roslyn/issues/17698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestRefReturns() { await TestWithPickMembersDialogAsync( @" using System; class Base { public virtual ref int X() => throw new NotImplementedException(); public virtual ref int Y => throw new NotImplementedException(); public virtual ref int this[int i] => throw new NotImplementedException(); } class Derived : Base { [||] }", @" using System; class Base { public virtual ref int X() => throw new NotImplementedException(); public virtual ref int Y => throw new NotImplementedException(); public virtual ref int this[int i] => throw new NotImplementedException(); } class Derived : Base { public override ref int this[int i] => ref base[i]; public override ref int Y => ref base.Y; public override ref int X() { return ref base.X(); } }", new[] { "X", "Y", "this[]" }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestInitOnlyProperty() { await TestWithPickMembersDialogAsync( @" class Base { public virtual int Property { init => throw new NotImplementedException(); } } class Derived : Base { [||] }", @" class Base { public virtual int Property { init => throw new NotImplementedException(); } } class Derived : Base { public override int Property { init => base.Property = value; } }", new[] { "Property" }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestInitOnlyIndexer() { await TestWithPickMembersDialogAsync( @" class Base { public virtual int this[int i] { init => throw new NotImplementedException(); } } class Derived : Base { [||] }", @" class Base { public virtual int this[int i] { init => throw new NotImplementedException(); } } class Derived : Base { public override int this[int i] { init => base[i] = value; } }", new[] { "this[]" }); } [WorkItem(21601, "https://github.com/dotnet/roslyn/issues/21601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestMissingInStaticClass1() { await TestMissingAsync( @" static class C { [||] }"); } [WorkItem(21601, "https://github.com/dotnet/roslyn/issues/21601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestMissingInStaticClass2() { await TestMissingAsync( @" static class [||]C { }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateOverrides; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateOverrides { public class GenerateOverridesTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new GenerateOverridesCodeRefactoringProvider((IPickMembersService)parameters.fixProviderData); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task Test1() { await TestWithPickMembersDialogAsync( @" class C { [||] }", @" class C { public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } }", new[] { "Equals", "GetHashCode", "ToString" }); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestAtEndOfFile() { await TestWithPickMembersDialogAsync( @" class C[||]", @" class C { public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } } ", new[] { "Equals", "GetHashCode", "ToString" }); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestOnRecordWithSemiColon() { await TestWithPickMembersDialogAsync(@" record C[||]; ", @" record C { public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } } ", new[] { "GetHashCode", "ToString" }); } [WorkItem(17698, "https://github.com/dotnet/roslyn/issues/17698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestRefReturns() { await TestWithPickMembersDialogAsync( @" using System; class Base { public virtual ref int X() => throw new NotImplementedException(); public virtual ref int Y => throw new NotImplementedException(); public virtual ref int this[int i] => throw new NotImplementedException(); } class Derived : Base { [||] }", @" using System; class Base { public virtual ref int X() => throw new NotImplementedException(); public virtual ref int Y => throw new NotImplementedException(); public virtual ref int this[int i] => throw new NotImplementedException(); } class Derived : Base { public override ref int this[int i] => ref base[i]; public override ref int Y => ref base.Y; public override ref int X() { return ref base.X(); } }", new[] { "X", "Y", "this[]" }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestInitOnlyProperty() { await TestWithPickMembersDialogAsync( @" class Base { public virtual int Property { init => throw new NotImplementedException(); } } class Derived : Base { [||] }", @" class Base { public virtual int Property { init => throw new NotImplementedException(); } } class Derived : Base { public override int Property { init => base.Property = value; } }", new[] { "Property" }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestInitOnlyIndexer() { await TestWithPickMembersDialogAsync( @" class Base { public virtual int this[int i] { init => throw new NotImplementedException(); } } class Derived : Base { [||] }", @" class Base { public virtual int this[int i] { init => throw new NotImplementedException(); } } class Derived : Base { public override int this[int i] { init => base[i] = value; } }", new[] { "this[]" }); } [WorkItem(21601, "https://github.com/dotnet/roslyn/issues/21601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestMissingInStaticClass1() { await TestMissingAsync( @" static class C { [||] }"); } [WorkItem(21601, "https://github.com/dotnet/roslyn/issues/21601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateOverrides)] public async Task TestMissingInStaticClass2() { await TestMissingAsync( @" static class [||]C { }"); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/VisualStudio/TestUtilities2/CodeModel/Mocks/MockVisualStudioWorkspace.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.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks Friend Class MockVisualStudioWorkspace Inherits VisualStudioWorkspace Private ReadOnly _workspace As TestWorkspace Private ReadOnly _fileCodeModels As New Dictionary(Of DocumentId, ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel)) Public Sub New(workspace As TestWorkspace) MyBase.New(workspace.Services.HostServices) _workspace = workspace SetCurrentSolution(workspace.CurrentSolution) End Sub Public Overrides Function CanApplyChange(feature As ApplyChangesKind) As Boolean Return _workspace.CanApplyChange(feature) End Function Protected Overrides Sub OnDocumentTextChanged(document As Document) Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.WithDocumentText(document.Id, document.GetTextAsync().Result))) SetCurrentSolution(_workspace.CurrentSolution) End Sub Public Overrides Sub CloseDocument(documentId As DocumentId) _workspace.CloseDocument(documentId) SetCurrentSolution(_workspace.CurrentSolution) End Sub Protected Overrides Sub ApplyDocumentRemoved(documentId As DocumentId) Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.RemoveDocument(documentId))) SetCurrentSolution(_workspace.CurrentSolution) End Sub Public Overrides Function GetHierarchy(projectId As ProjectId) As Microsoft.VisualStudio.Shell.Interop.IVsHierarchy Return Nothing End Function Friend Overrides Function GetProjectGuid(projectId As ProjectId) As Guid Return Guid.Empty End Function Friend Overrides Function OpenInvisibleEditor(documentId As DocumentId) As IInvisibleEditor Return New MockInvisibleEditor(documentId, _workspace) End Function Public Overrides Function GetFileCodeModel(documentId As DocumentId) As EnvDTE.FileCodeModel Return _fileCodeModels(documentId).Handle End Function Public Overrides Function TryGoToDefinition(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean Throw New NotImplementedException() End Function Public Overrides Function TryGoToDefinitionAsync(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Task(Of Boolean) Throw New NotImplementedException() End Function Public Overrides Function TryFindAllReferences(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean Throw New NotImplementedException() End Function Public Overrides Sub DisplayReferencedSymbols(solution As Solution, referencedSymbols As IEnumerable(Of ReferencedSymbol)) Throw New NotImplementedException() End Sub Friend Overrides Function GetBrowseObject(symbolListItem As SymbolListItem) As Object Throw New NotImplementedException() End Function Friend Sub SetFileCodeModel(id As DocumentId, fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel)) _fileCodeModels.Add(id, fileCodeModel) End Sub Friend Function GetFileCodeModelComHandle(id As DocumentId) As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel) Return _fileCodeModels(id) End Function Friend Overrides Function TryGetRuleSetPathForProject(projectId As ProjectId) As String Throw New NotImplementedException() End Function End Class Public Class MockInvisibleEditor Implements IInvisibleEditor Private ReadOnly _documentId As DocumentId Private ReadOnly _workspace As TestWorkspace Private ReadOnly _needsClose As Boolean Public Sub New(documentId As DocumentId, workspace As TestWorkspace) Me._documentId = documentId Me._workspace = workspace If Not workspace.IsDocumentOpen(documentId) Then _workspace.OpenDocument(documentId) _needsClose = True End If End Sub Public ReadOnly Property TextBuffer As Global.Microsoft.VisualStudio.Text.ITextBuffer Implements IInvisibleEditor.TextBuffer Get Return Me._workspace.GetTestDocument(Me._documentId).GetTextBuffer() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose If _needsClose Then _workspace.CloseDocument(_documentId) End If 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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.Mocks Friend Class MockVisualStudioWorkspace Inherits VisualStudioWorkspace Private ReadOnly _workspace As TestWorkspace Private ReadOnly _fileCodeModels As New Dictionary(Of DocumentId, ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel)) Public Sub New(workspace As TestWorkspace) MyBase.New(workspace.Services.HostServices) _workspace = workspace SetCurrentSolution(workspace.CurrentSolution) End Sub Public Overrides Function CanApplyChange(feature As ApplyChangesKind) As Boolean Return _workspace.CanApplyChange(feature) End Function Protected Overrides Sub OnDocumentTextChanged(document As Document) Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.WithDocumentText(document.Id, document.GetTextAsync().Result))) SetCurrentSolution(_workspace.CurrentSolution) End Sub Public Overrides Sub CloseDocument(documentId As DocumentId) _workspace.CloseDocument(documentId) SetCurrentSolution(_workspace.CurrentSolution) End Sub Protected Overrides Sub ApplyDocumentRemoved(documentId As DocumentId) Assert.True(_workspace.TryApplyChanges(_workspace.CurrentSolution.RemoveDocument(documentId))) SetCurrentSolution(_workspace.CurrentSolution) End Sub Public Overrides Function GetHierarchy(projectId As ProjectId) As Microsoft.VisualStudio.Shell.Interop.IVsHierarchy Return Nothing End Function Friend Overrides Function GetProjectGuid(projectId As ProjectId) As Guid Return Guid.Empty End Function Friend Overrides Function OpenInvisibleEditor(documentId As DocumentId) As IInvisibleEditor Return New MockInvisibleEditor(documentId, _workspace) End Function Public Overrides Function GetFileCodeModel(documentId As DocumentId) As EnvDTE.FileCodeModel Return _fileCodeModels(documentId).Handle End Function Public Overrides Function TryGoToDefinition(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean Throw New NotImplementedException() End Function Public Overrides Function TryGoToDefinitionAsync(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Task(Of Boolean) Throw New NotImplementedException() End Function Public Overrides Function TryFindAllReferences(symbol As ISymbol, project As Project, cancellationToken As CancellationToken) As Boolean Throw New NotImplementedException() End Function Public Overrides Sub DisplayReferencedSymbols(solution As Solution, referencedSymbols As IEnumerable(Of ReferencedSymbol)) Throw New NotImplementedException() End Sub Friend Overrides Function GetBrowseObject(symbolListItem As SymbolListItem) As Object Throw New NotImplementedException() End Function Friend Sub SetFileCodeModel(id As DocumentId, fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel)) _fileCodeModels.Add(id, fileCodeModel) End Sub Friend Function GetFileCodeModelComHandle(id As DocumentId) As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel) Return _fileCodeModels(id) End Function Friend Overrides Function TryGetRuleSetPathForProject(projectId As ProjectId) As String Throw New NotImplementedException() End Function End Class Public Class MockInvisibleEditor Implements IInvisibleEditor Private ReadOnly _documentId As DocumentId Private ReadOnly _workspace As TestWorkspace Private ReadOnly _needsClose As Boolean Public Sub New(documentId As DocumentId, workspace As TestWorkspace) Me._documentId = documentId Me._workspace = workspace If Not workspace.IsDocumentOpen(documentId) Then _workspace.OpenDocument(documentId) _needsClose = True End If End Sub Public ReadOnly Property TextBuffer As Global.Microsoft.VisualStudio.Text.ITextBuffer Implements IInvisibleEditor.TextBuffer Get Return Me._workspace.GetTestDocument(Me._documentId).GetTextBuffer() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose If _needsClose Then _workspace.CloseDocument(_documentId) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Reverse.cs
// Licensed to the .NET Foundation under one or more 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/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Reverse.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.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse(int listLength) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(); for (int i = 0; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[listBefore.Count - (i + 1)]); //"Expect them to be the same." } } [Theory] [InlineData(10, 0, 10)] [InlineData(10, 3, 3)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_int_int(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [InlineData(10, 3, 3)] [InlineData(10, 0, 10)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_RepeatedValues(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(1); for (int i = 1; i < listLength; i++) list.Add(list[0]); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_InvalidParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(listLength ,1 ), Tuple.Create(listLength+1 ,0 ), Tuple.Create(listLength+1 ,1 ), Tuple.Create(listLength ,2 ), Tuple.Create(listLength/2 ,listLength/2+1), Tuple.Create(listLength-1 ,2 ), Tuple.Create(listLength-2 ,3 ), Tuple.Create(1 ,listLength ), Tuple.Create(0 ,listLength+1 ), Tuple.Create(1 ,listLength+1 ), Tuple.Create(2 ,listLength ), Tuple.Create(listLength/2+1 ,listLength/2 ), Tuple.Create(2 ,listLength-1 ), Tuple.Create(3 ,listLength-2 ), }; Assert.All(InvalidParameters, invalidSet => { if (invalidSet.Item1 >= 0 && invalidSet.Item2 >= 0) Assert.Throws<ArgumentException>(null, () => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_NegativeParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(0 ,-1), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } } }
// Licensed to the .NET Foundation under one or more 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/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Reverse.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.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse(int listLength) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(); for (int i = 0; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[listBefore.Count - (i + 1)]); //"Expect them to be the same." } } [Theory] [InlineData(10, 0, 10)] [InlineData(10, 3, 3)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_int_int(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [InlineData(10, 3, 3)] [InlineData(10, 0, 10)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_RepeatedValues(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(1); for (int i = 1; i < listLength; i++) list.Add(list[0]); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_InvalidParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(listLength ,1 ), Tuple.Create(listLength+1 ,0 ), Tuple.Create(listLength+1 ,1 ), Tuple.Create(listLength ,2 ), Tuple.Create(listLength/2 ,listLength/2+1), Tuple.Create(listLength-1 ,2 ), Tuple.Create(listLength-2 ,3 ), Tuple.Create(1 ,listLength ), Tuple.Create(0 ,listLength+1 ), Tuple.Create(1 ,listLength+1 ), Tuple.Create(2 ,listLength ), Tuple.Create(listLength/2+1 ,listLength/2 ), Tuple.Create(2 ,listLength-1 ), Tuple.Create(3 ,listLength-2 ), }; Assert.All(InvalidParameters, invalidSet => { if (invalidSet.Item1 >= 0 && invalidSet.Item2 >= 0) Assert.Throws<ArgumentException>(null, () => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_NegativeParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(0 ,-1), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/Core/Portable/Symbols/ILabelSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a label in method body /// </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 ILabelSymbol : ISymbol { /// <summary> /// Gets the immediately containing <see cref="IMethodSymbol"/> of this <see cref="ILocalSymbol"/>. /// </summary> IMethodSymbol ContainingMethod { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a label in method body /// </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 ILabelSymbol : ISymbol { /// <summary> /// Gets the immediately containing <see cref="IMethodSymbol"/> of this <see cref="ILocalSymbol"/>. /// </summary> IMethodSymbol ContainingMethod { get; } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/Test/Structure/StructureTaggerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class StructureTaggerTests { [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task CSharpOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"using System; namespace MyNamespace { #region MyRegion public class MyClass { static void Main(string[] args) { if (false) { return; } int x = 5; } } #endregion }"; using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(17, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(14, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal("#region MyRegion", GetHeaderText(regionTag)); }, classTag => { Assert.False(classTag.IsImplementation); Assert.Equal(12, GetCollapsedHintLineCount(classTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, classTag.Type); Assert.Equal("public class MyClass", GetHeaderText(classTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("static void Main(string[] args)", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(4, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("if (false)", GetHeaderText(ifTag)); }); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task VisualBasicOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"Imports System Namespace MyNamespace #Region ""MyRegion"" Module M Sub Main(args As String()) If False Then Return End If Dim x As Integer = 5 End Sub End Module #End Region End Namespace"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(13, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("Namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(11, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal(@"#Region ""MyRegion""", GetHeaderText(regionTag)); }, moduleTag => { Assert.False(moduleTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(moduleTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, moduleTag.Type); Assert.Equal("Module M", GetHeaderText(moduleTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(7, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("Sub Main(args As String())", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(3, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("If False Then", GetHeaderText(ifTag)); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task OutliningTaggerTooltipText() { var code = @"Module Module1 Sub Main(args As String()) End Sub End Module"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); var tags = await GetTagsFromWorkspaceAsync(workspace); var hints = tags.Select(x => x.GetCollapsedHintForm()).Cast<ViewHostingControl>().ToArray(); Assert.Equal("Sub Main(args As String())\r\nEnd Sub", hints[1].GetText_TestOnly()); // method hints.Do(v => v.TextView_TestOnly.Close()); } private static async Task<List<IStructureTag>> GetTagsFromWorkspaceAsync(TestWorkspace workspace) { var hostdoc = workspace.Documents.First(); var view = hostdoc.GetTextView(); var provider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var context = new TaggerContext<IStructureTag>(document, view.TextSnapshot); await provider.GetTestAccessor().ProduceTagsAsync(context); return context.tagSpans.Select(x => x.Tag).OrderBy(t => t.OutliningSpan.Value.Start).ToList(); } private static string GetHeaderText(IStructureTag namespaceTag) { return namespaceTag.Snapshot.GetText(namespaceTag.HeaderSpan.Value); } private static int GetCollapsedHintLineCount(IStructureTag tag) { var control = Assert.IsType<ViewHostingControl>(tag.GetCollapsedHintForm()); var view = control.TextView_TestOnly; try { return view.TextSnapshot.LineCount; } finally { view.Close(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class StructureTaggerTests { [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task CSharpOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"using System; namespace MyNamespace { #region MyRegion public class MyClass { static void Main(string[] args) { if (false) { return; } int x = 5; } } #endregion }"; using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(17, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(14, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal("#region MyRegion", GetHeaderText(regionTag)); }, classTag => { Assert.False(classTag.IsImplementation); Assert.Equal(12, GetCollapsedHintLineCount(classTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, classTag.Type); Assert.Equal("public class MyClass", GetHeaderText(classTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("static void Main(string[] args)", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(4, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("if (false)", GetHeaderText(ifTag)); }); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task VisualBasicOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"Imports System Namespace MyNamespace #Region ""MyRegion"" Module M Sub Main(args As String()) If False Then Return End If Dim x As Integer = 5 End Sub End Module #End Region End Namespace"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(13, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("Namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(11, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal(@"#Region ""MyRegion""", GetHeaderText(regionTag)); }, moduleTag => { Assert.False(moduleTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(moduleTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, moduleTag.Type); Assert.Equal("Module M", GetHeaderText(moduleTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(7, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("Sub Main(args As String())", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(3, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("If False Then", GetHeaderText(ifTag)); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task OutliningTaggerTooltipText() { var code = @"Module Module1 Sub Main(args As String()) End Sub End Module"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); var tags = await GetTagsFromWorkspaceAsync(workspace); var hints = tags.Select(x => x.GetCollapsedHintForm()).Cast<ViewHostingControl>().ToArray(); Assert.Equal("Sub Main(args As String())\r\nEnd Sub", hints[1].GetText_TestOnly()); // method hints.Do(v => v.TextView_TestOnly.Close()); } private static async Task<List<IStructureTag>> GetTagsFromWorkspaceAsync(TestWorkspace workspace) { var hostdoc = workspace.Documents.First(); var view = hostdoc.GetTextView(); var provider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var context = new TaggerContext<IStructureTag>(document, view.TextSnapshot); await provider.GetTestAccessor().ProduceTagsAsync(context); return context.tagSpans.Select(x => x.Tag).OrderBy(t => t.OutliningSpan.Value.Start).ToList(); } private static string GetHeaderText(IStructureTag namespaceTag) { return namespaceTag.Snapshot.GetText(namespaceTag.HeaderSpan.Value); } private static int GetCollapsedHintLineCount(IStructureTag tag) { var control = Assert.IsType<ViewHostingControl>(tag.GetCollapsedHintForm()); var view = control.TextView_TestOnly; try { return view.TextSnapshot.LineCount; } finally { view.Close(); } } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedAttributeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Cci; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated and embedded attribute type. /// This type has the following properties: /// 1) It is non-generic, sealed, internal, non-static class. /// 2) It derives from System.Attribute /// 3) It has Microsoft.CodeAnalysis.EmbeddedAttribute /// 4) It has System.Runtime.CompilerServices.CompilerGeneratedAttribute /// </summary> internal abstract class SynthesizedEmbeddedAttributeSymbolBase : NamedTypeSymbol { private readonly string _name; private readonly NamedTypeSymbol _baseType; private readonly NamespaceSymbol _namespace; private readonly ModuleSymbol _module; public SynthesizedEmbeddedAttributeSymbolBase( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) { Debug.Assert(name is object); Debug.Assert(containingNamespace is object); Debug.Assert(containingModule is object); Debug.Assert(baseType is object); _name = name; _namespace = containingNamespace; _module = containingModule; _baseType = baseType; } public new abstract ImmutableArray<MethodSymbol> Constructors { get; } public override int Arity => 0; public override ImmutableArray<TypeParameterSymbol> TypeParameters => ImmutableArray<TypeParameterSymbol>.Empty; public override bool IsImplicitlyDeclared => true; internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed; public override NamedTypeSymbol ConstructedFrom => this; public override bool MightContainExtensionMethods => false; public override string Name => _name; public override IEnumerable<string> MemberNames => Constructors.Select(m => m.Name); public override Accessibility DeclaredAccessibility => Accessibility.Internal; public override TypeKind TypeKind => TypeKind.Class; public override Symbol ContainingSymbol => _namespace; internal override ModuleSymbol ContainingModule => _module; public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; public override NamespaceSymbol ContainingNamespace => _namespace; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsStatic => false; public override bool IsRefLikeType => false; public override bool IsReadOnly => false; public override bool IsAbstract => false; public override bool IsSealed => true; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray<TypeWithAnnotations>.Empty; internal override bool MangleName => false; internal override bool HasCodeAnalysisEmbeddedAttribute => true; internal override bool IsInterpolatedStringHandlerType => false; internal override bool HasSpecialName => false; internal override bool IsComImport => false; internal override bool IsWindowsRuntimeImport => false; internal override bool ShouldAddWinRTMembers => false; public override bool IsSerializable => false; public sealed override bool AreLocalsZeroed => ContainingModule.AreLocalsZeroed; internal override TypeLayout Layout => default; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; internal override bool HasDeclarativeSecurity => false; internal override bool IsInterface => false; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _baseType; internal override ObsoleteAttributeData ObsoleteAttributeData => null; protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers() => Constructors.CastArray<Symbol>(); public override ImmutableArray<Symbol> GetMembers(string name) => name == WellKnownMemberNames.InstanceConstructorName ? Constructors.CastArray<Symbol>() : ImmutableArray<Symbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override AttributeUsageInfo GetAttributeUsageInfo() => AttributeUsageInfo.Default; internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => _baseType; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => GetMembers(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => GetMembers(name); internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => SpecializedCollections.EmptyEnumerable<FieldSymbol>(); internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => ImmutableArray<NamedTypeSymbol>.Empty; internal override IEnumerable<SecurityAttribute> GetSecurityInformation() => null; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AddSynthesizedAttribute( ref attributes, moduleBuilder.Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeEmbeddedAttribute()); var usageInfo = GetAttributeUsageInfo(); if (usageInfo != AttributeUsageInfo.Default) { AddSynthesizedAttribute( ref attributes, moduleBuilder.Compilation.SynthesizeAttributeUsageAttribute(usageInfo.ValidTargets, usageInfo.AllowMultiple, usageInfo.Inherited)); } } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } /// <summary> /// Represents a compiler generated and embedded attribute type with a single default constructor /// </summary> internal sealed class SynthesizedEmbeddedAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase { private readonly ImmutableArray<MethodSymbol> _constructors; public SynthesizedEmbeddedAttributeSymbol( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) : base(name, containingNamespace, containingModule, baseType) { _constructors = ImmutableArray.Create<MethodSymbol>(new SynthesizedEmbeddedAttributeConstructorSymbol(this, m => ImmutableArray<ParameterSymbol>.Empty)); } public override ImmutableArray<MethodSymbol> Constructors => _constructors; internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; } internal sealed class SynthesizedEmbeddedAttributeConstructorSymbol : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; internal SynthesizedEmbeddedAttributeConstructorSymbol( NamedTypeSymbol containingType, Func<MethodSymbol, ImmutableArray<ParameterSymbol>> getParameters) : base(containingType) { _parameters = getParameters(this); } public override ImmutableArray<ParameterSymbol> Parameters => _parameters; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { GenerateMethodBodyCore(compilationState, diagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Cci; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated and embedded attribute type. /// This type has the following properties: /// 1) It is non-generic, sealed, internal, non-static class. /// 2) It derives from System.Attribute /// 3) It has Microsoft.CodeAnalysis.EmbeddedAttribute /// 4) It has System.Runtime.CompilerServices.CompilerGeneratedAttribute /// </summary> internal abstract class SynthesizedEmbeddedAttributeSymbolBase : NamedTypeSymbol { private readonly string _name; private readonly NamedTypeSymbol _baseType; private readonly NamespaceSymbol _namespace; private readonly ModuleSymbol _module; public SynthesizedEmbeddedAttributeSymbolBase( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) { Debug.Assert(name is object); Debug.Assert(containingNamespace is object); Debug.Assert(containingModule is object); Debug.Assert(baseType is object); _name = name; _namespace = containingNamespace; _module = containingModule; _baseType = baseType; } public new abstract ImmutableArray<MethodSymbol> Constructors { get; } public override int Arity => 0; public override ImmutableArray<TypeParameterSymbol> TypeParameters => ImmutableArray<TypeParameterSymbol>.Empty; public override bool IsImplicitlyDeclared => true; internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed; public override NamedTypeSymbol ConstructedFrom => this; public override bool MightContainExtensionMethods => false; public override string Name => _name; public override IEnumerable<string> MemberNames => Constructors.Select(m => m.Name); public override Accessibility DeclaredAccessibility => Accessibility.Internal; public override TypeKind TypeKind => TypeKind.Class; public override Symbol ContainingSymbol => _namespace; internal override ModuleSymbol ContainingModule => _module; public override AssemblySymbol ContainingAssembly => _module.ContainingAssembly; public override NamespaceSymbol ContainingNamespace => _namespace; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsStatic => false; public override bool IsRefLikeType => false; public override bool IsReadOnly => false; public override bool IsAbstract => false; public override bool IsSealed => true; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics => ImmutableArray<TypeWithAnnotations>.Empty; internal override bool MangleName => false; internal override bool HasCodeAnalysisEmbeddedAttribute => true; internal override bool IsInterpolatedStringHandlerType => false; internal override bool HasSpecialName => false; internal override bool IsComImport => false; internal override bool IsWindowsRuntimeImport => false; internal override bool ShouldAddWinRTMembers => false; public override bool IsSerializable => false; public sealed override bool AreLocalsZeroed => ContainingModule.AreLocalsZeroed; internal override TypeLayout Layout => default; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; internal override bool HasDeclarativeSecurity => false; internal override bool IsInterface => false; internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => _baseType; internal override ObsoleteAttributeData ObsoleteAttributeData => null; protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; public override ImmutableArray<Symbol> GetMembers() => Constructors.CastArray<Symbol>(); public override ImmutableArray<Symbol> GetMembers(string name) => name == WellKnownMemberNames.InstanceConstructorName ? Constructors.CastArray<Symbol>() : ImmutableArray<Symbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override AttributeUsageInfo GetAttributeUsageInfo() => AttributeUsageInfo.Default; internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => _baseType; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => GetMembers(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => GetMembers(name); internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => SpecializedCollections.EmptyEnumerable<FieldSymbol>(); internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => ImmutableArray<NamedTypeSymbol>.Empty; internal override IEnumerable<SecurityAttribute> GetSecurityInformation() => null; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); AddSynthesizedAttribute( ref attributes, moduleBuilder.Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeEmbeddedAttribute()); var usageInfo = GetAttributeUsageInfo(); if (usageInfo != AttributeUsageInfo.Default) { AddSynthesizedAttribute( ref attributes, moduleBuilder.Compilation.SynthesizeAttributeUsageAttribute(usageInfo.ValidTargets, usageInfo.AllowMultiple, usageInfo.Inherited)); } } internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } /// <summary> /// Represents a compiler generated and embedded attribute type with a single default constructor /// </summary> internal sealed class SynthesizedEmbeddedAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase { private readonly ImmutableArray<MethodSymbol> _constructors; public SynthesizedEmbeddedAttributeSymbol( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol baseType) : base(name, containingNamespace, containingModule, baseType) { _constructors = ImmutableArray.Create<MethodSymbol>(new SynthesizedEmbeddedAttributeConstructorSymbol(this, m => ImmutableArray<ParameterSymbol>.Empty)); } public override ImmutableArray<MethodSymbol> Constructors => _constructors; internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; } internal sealed class SynthesizedEmbeddedAttributeConstructorSymbol : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; internal SynthesizedEmbeddedAttributeConstructorSymbol( NamedTypeSymbol containingType, Func<MethodSymbol, ImmutableArray<ParameterSymbol>> getParameters) : base(containingType) { _parameters = getParameters(this); } public override ImmutableArray<ParameterSymbol> Parameters => _parameters; internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { GenerateMethodBodyCore(compilationState, diagnostics); } } }
-1