repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.FactoryBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Runtime; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.ServiceHub.Framework; using Microsoft.ServiceHub.Framework.Services; using Nerdbank.Streams; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal abstract partial class BrokeredServiceBase { internal interface IFactory { object Create(IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker); Type ServiceType { get; } } internal abstract class FactoryBase<TService> : IServiceHubServiceFactory, IFactory where TService : class { static FactoryBase() { Debug.Assert(typeof(TService).IsInterface); } protected abstract TService CreateService(in ServiceConstructionArguments arguments); protected virtual TService CreateService( in ServiceConstructionArguments arguments, ServiceRpcDescriptor descriptor, ServiceRpcDescriptor.RpcConnection serverConnection, object? clientRpcTarget) => CreateService(arguments); public Task<object> CreateAsync( Stream stream, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker, AuthorizationServiceClient? authorizationServiceClient) { // Dispose the AuthorizationServiceClient since we won't be using it authorizationServiceClient?.Dispose(); return Task.FromResult((object)Create( stream.UsePipe(), hostProvidedServices, serviceActivationOptions, serviceBroker)); } object IFactory.Create(IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker) => Create(pipe, hostProvidedServices, serviceActivationOptions, serviceBroker); Type IFactory.ServiceType => typeof(TService); internal TService Create( IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker) { // Register this service broker globally (if it's the first we encounter) so it can be used by other // global services that need it. GlobalServiceBroker.RegisterServiceBroker(serviceBroker); var descriptor = ServiceDescriptors.Instance.GetServiceDescriptorForServiceFactory(typeof(TService)); var serviceHubTraceSource = (TraceSource)hostProvidedServices.GetService(typeof(TraceSource)); var serverConnection = descriptor.WithTraceSource(serviceHubTraceSource).ConstructRpcConnection(pipe); var args = new ServiceConstructionArguments(hostProvidedServices, serviceBroker); var service = CreateService(args, descriptor, serverConnection, serviceActivationOptions.ClientRpcTarget); serverConnection.AddLocalRpcTarget(service); serverConnection.StartListening(); return service; } } internal abstract class FactoryBase<TService, TCallback> : FactoryBase<TService> where TService : class where TCallback : class { static FactoryBase() { Debug.Assert(typeof(TCallback).IsInterface); } protected abstract TService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<TCallback> callback); protected sealed override TService CreateService(in ServiceConstructionArguments arguments) => throw ExceptionUtilities.Unreachable; protected sealed override TService CreateService( in ServiceConstructionArguments arguments, ServiceRpcDescriptor descriptor, ServiceRpcDescriptor.RpcConnection serverConnection, object? clientRpcTarget) { Contract.ThrowIfNull(descriptor.ClientInterface); var callback = (TCallback)(clientRpcTarget ?? serverConnection.ConstructRpcClient(descriptor.ClientInterface)); return CreateService(arguments, new RemoteCallback<TCallback>(callback)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Runtime; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.ServiceHub.Framework; using Microsoft.ServiceHub.Framework.Services; using Nerdbank.Streams; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal abstract partial class BrokeredServiceBase { internal interface IFactory { object Create(IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker); Type ServiceType { get; } } internal abstract class FactoryBase<TService> : IServiceHubServiceFactory, IFactory where TService : class { static FactoryBase() { Debug.Assert(typeof(TService).IsInterface); } protected abstract TService CreateService(in ServiceConstructionArguments arguments); protected virtual TService CreateService( in ServiceConstructionArguments arguments, ServiceRpcDescriptor descriptor, ServiceRpcDescriptor.RpcConnection serverConnection, object? clientRpcTarget) => CreateService(arguments); public Task<object> CreateAsync( Stream stream, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker, AuthorizationServiceClient? authorizationServiceClient) { // Dispose the AuthorizationServiceClient since we won't be using it authorizationServiceClient?.Dispose(); return Task.FromResult((object)Create( stream.UsePipe(), hostProvidedServices, serviceActivationOptions, serviceBroker)); } object IFactory.Create(IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker) => Create(pipe, hostProvidedServices, serviceActivationOptions, serviceBroker); Type IFactory.ServiceType => typeof(TService); internal TService Create( IDuplexPipe pipe, IServiceProvider hostProvidedServices, ServiceActivationOptions serviceActivationOptions, IServiceBroker serviceBroker) { // Register this service broker globally (if it's the first we encounter) so it can be used by other // global services that need it. GlobalServiceBroker.RegisterServiceBroker(serviceBroker); var descriptor = ServiceDescriptors.Instance.GetServiceDescriptorForServiceFactory(typeof(TService)); var serviceHubTraceSource = (TraceSource)hostProvidedServices.GetService(typeof(TraceSource)); var serverConnection = descriptor.WithTraceSource(serviceHubTraceSource).ConstructRpcConnection(pipe); var args = new ServiceConstructionArguments(hostProvidedServices, serviceBroker); var service = CreateService(args, descriptor, serverConnection, serviceActivationOptions.ClientRpcTarget); serverConnection.AddLocalRpcTarget(service); serverConnection.StartListening(); return service; } } internal abstract class FactoryBase<TService, TCallback> : FactoryBase<TService> where TService : class where TCallback : class { static FactoryBase() { Debug.Assert(typeof(TCallback).IsInterface); } protected abstract TService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<TCallback> callback); protected sealed override TService CreateService(in ServiceConstructionArguments arguments) => throw ExceptionUtilities.Unreachable; protected sealed override TService CreateService( in ServiceConstructionArguments arguments, ServiceRpcDescriptor descriptor, ServiceRpcDescriptor.RpcConnection serverConnection, object? clientRpcTarget) { Contract.ThrowIfNull(descriptor.ClientInterface); var callback = (TCallback)(clientRpcTarget ?? serverConnection.ConstructRpcClient(descriptor.ClientInterface)); return CreateService(arguments, new RemoteCallback<TCallback>(callback)); } } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/VisualBasic/Portable/TodoComments/BasicTodoCommentIncrementalAnalyzerProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.TodoComments Namespace Microsoft.CodeAnalysis.VisualBasic.TodoComments <ExportLanguageServiceFactory(GetType(ITodoCommentService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicTodoCommentServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicTodoCommentService() End Function End Class Friend Class VisualBasicTodoCommentService Inherits AbstractTodoCommentService Protected Overrides Sub AppendTodoComments( commentDescriptors As ImmutableArray(Of TodoCommentDescriptor), document As SyntacticDocument, trivia As SyntaxTrivia, todoList As ArrayBuilder(Of TodoComment)) If PreprocessorHasComment(trivia) Then Dim commentTrivia = trivia.GetStructure().DescendantTrivia().First(Function(t) t.RawKind = SyntaxKind.CommentTrivia) AppendTodoCommentInfoFromSingleLine(commentDescriptors, commentTrivia.ToFullString(), commentTrivia.FullSpan.Start, todoList) Return End If If IsSingleLineComment(trivia) Then ProcessMultilineComment(commentDescriptors, document, trivia, postfixLength:=0, todoList:=todoList) Return End If Throw ExceptionUtilities.Unreachable End Sub Protected Overrides Function GetNormalizedText(message As String) As String Return SyntaxFacts.MakeHalfWidthIdentifier(message) End Function Protected Overrides Function IsIdentifierCharacter(ch As Char) As Boolean Return SyntaxFacts.IsIdentifierPartCharacter(ch) End Function Protected Overrides Function GetCommentStartingIndex(message As String) As Integer ' 3 for REM Dim index = GetFirstCharacterIndex(message) If index >= message.Length OrElse index > message.Length - 3 Then Return index End If Dim remText = message.Substring(index, "REM".Length) If SyntaxFacts.GetKeywordKind(remText) = SyntaxKind.REMKeyword Then Return GetFirstCharacterIndex(message, index + remText.Length) End If Return index End Function Private Shared Function GetFirstCharacterIndex(message As String, Optional start As Integer = 0) As Integer Dim index = GetFirstNonWhitespace(message, start) Dim singleQuote = 0 For i = index To message.Length - 1 Step 1 If IsSingleQuote(message(i)) AndAlso singleQuote < 3 Then singleQuote = singleQuote + 1 Else If singleQuote = 1 OrElse singleQuote = 3 Then Return GetFirstNonWhitespace(message, i) Else Return index End If End If Next Return message.Length End Function Private Shared Function GetFirstNonWhitespace(message As String, start As Integer) As Integer For i = start To message.Length - 1 Step 1 If Not SyntaxFacts.IsWhitespace(message(i)) Then Return i End If Next Return message.Length End Function Protected Overrides Function IsMultilineComment(trivia As SyntaxTrivia) As Boolean ' vb doesn't have multiline comment Return False End Function Protected Overrides Function IsSingleLineComment(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.CommentTrivia OrElse trivia.RawKind = SyntaxKind.DocumentationCommentTrivia End Function Protected Overrides Function PreprocessorHasComment(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(CType(trivia.RawKind, SyntaxKind)) AndAlso trivia.GetStructure().DescendantTrivia().Any(Function(t) t.RawKind = SyntaxKind.CommentTrivia) End Function ' TODO: remove this if SyntaxFacts.IsSingleQuote become public Private Const s_DWCH_SQ As Char = ChrW(&HFF07) '// DW single quote Private Const s_DWCH_LSMART_Q As Char = ChrW(&H2018S) '// DW left single smart quote Private Const s_DWCH_RSMART_Q As Char = ChrW(&H2019S) '// DW right single smart quote Private Shared Function IsSingleQuote(c As Char) As Boolean ' // Besides the half width and full width ', we also check for Unicode ' // LEFT SINGLE QUOTATION MARK and RIGHT SINGLE QUOTATION MARK because ' // IME editors paste them in. This isn't really technically correct ' // because we ignore the left-ness or right-ness, but see VS 170991 Return c = "'"c OrElse (c >= s_DWCH_LSMART_Q AndAlso (c = s_DWCH_SQ Or c = s_DWCH_LSMART_Q Or c = s_DWCH_RSMART_Q)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.TodoComments Namespace Microsoft.CodeAnalysis.VisualBasic.TodoComments <ExportLanguageServiceFactory(GetType(ITodoCommentService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicTodoCommentServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicTodoCommentService() End Function End Class Friend Class VisualBasicTodoCommentService Inherits AbstractTodoCommentService Protected Overrides Sub AppendTodoComments( commentDescriptors As ImmutableArray(Of TodoCommentDescriptor), document As SyntacticDocument, trivia As SyntaxTrivia, todoList As ArrayBuilder(Of TodoComment)) If PreprocessorHasComment(trivia) Then Dim commentTrivia = trivia.GetStructure().DescendantTrivia().First(Function(t) t.RawKind = SyntaxKind.CommentTrivia) AppendTodoCommentInfoFromSingleLine(commentDescriptors, commentTrivia.ToFullString(), commentTrivia.FullSpan.Start, todoList) Return End If If IsSingleLineComment(trivia) Then ProcessMultilineComment(commentDescriptors, document, trivia, postfixLength:=0, todoList:=todoList) Return End If Throw ExceptionUtilities.Unreachable End Sub Protected Overrides Function GetNormalizedText(message As String) As String Return SyntaxFacts.MakeHalfWidthIdentifier(message) End Function Protected Overrides Function IsIdentifierCharacter(ch As Char) As Boolean Return SyntaxFacts.IsIdentifierPartCharacter(ch) End Function Protected Overrides Function GetCommentStartingIndex(message As String) As Integer ' 3 for REM Dim index = GetFirstCharacterIndex(message) If index >= message.Length OrElse index > message.Length - 3 Then Return index End If Dim remText = message.Substring(index, "REM".Length) If SyntaxFacts.GetKeywordKind(remText) = SyntaxKind.REMKeyword Then Return GetFirstCharacterIndex(message, index + remText.Length) End If Return index End Function Private Shared Function GetFirstCharacterIndex(message As String, Optional start As Integer = 0) As Integer Dim index = GetFirstNonWhitespace(message, start) Dim singleQuote = 0 For i = index To message.Length - 1 Step 1 If IsSingleQuote(message(i)) AndAlso singleQuote < 3 Then singleQuote = singleQuote + 1 Else If singleQuote = 1 OrElse singleQuote = 3 Then Return GetFirstNonWhitespace(message, i) Else Return index End If End If Next Return message.Length End Function Private Shared Function GetFirstNonWhitespace(message As String, start As Integer) As Integer For i = start To message.Length - 1 Step 1 If Not SyntaxFacts.IsWhitespace(message(i)) Then Return i End If Next Return message.Length End Function Protected Overrides Function IsMultilineComment(trivia As SyntaxTrivia) As Boolean ' vb doesn't have multiline comment Return False End Function Protected Overrides Function IsSingleLineComment(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.CommentTrivia OrElse trivia.RawKind = SyntaxKind.DocumentationCommentTrivia End Function Protected Overrides Function PreprocessorHasComment(trivia As SyntaxTrivia) As Boolean Return SyntaxFacts.IsPreprocessorDirective(CType(trivia.RawKind, SyntaxKind)) AndAlso trivia.GetStructure().DescendantTrivia().Any(Function(t) t.RawKind = SyntaxKind.CommentTrivia) End Function ' TODO: remove this if SyntaxFacts.IsSingleQuote become public Private Const s_DWCH_SQ As Char = ChrW(&HFF07) '// DW single quote Private Const s_DWCH_LSMART_Q As Char = ChrW(&H2018S) '// DW left single smart quote Private Const s_DWCH_RSMART_Q As Char = ChrW(&H2019S) '// DW right single smart quote Private Shared Function IsSingleQuote(c As Char) As Boolean ' // Besides the half width and full width ', we also check for Unicode ' // LEFT SINGLE QUOTATION MARK and RIGHT SINGLE QUOTATION MARK because ' // IME editors paste them in. This isn't really technically correct ' // because we ignore the left-ness or right-ness, but see VS 170991 Return c = "'"c OrElse (c >= s_DWCH_LSMART_Q AndAlso (c = s_DWCH_SQ Or c = s_DWCH_LSMART_Q Or c = s_DWCH_RSMART_Q)) End Function End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/ContextQuery/SyntaxContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery { internal abstract class SyntaxContext { private ISet<INamedTypeSymbol> _outerTypes; protected SyntaxContext( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken leftToken, SyntaxToken targetToken, bool isTypeContext, bool isNamespaceContext, bool isNamespaceDeclarationNameContext, bool isPreProcessorDirectiveContext, bool isPreProcessorExpressionContext, bool isRightOfNameSeparator, bool isStatementContext, bool isAnyExpressionContext, bool isAttributeNameContext, bool isEnumTypeMemberAccessContext, bool isNameOfContext, bool isInQuery, bool isInImportsDirective, bool isWithinAsyncMethod, bool isPossibleTupleContext, bool isAtStartOfPattern, bool isAtEndOfPattern, bool isRightSideOfNumericType, bool isOnArgumentListBracketOrComma, CancellationToken cancellationToken) { this.Workspace = workspace; this.SemanticModel = semanticModel; this.SyntaxTree = semanticModel.SyntaxTree; this.Position = position; this.LeftToken = leftToken; this.TargetToken = targetToken; this.IsTypeContext = isTypeContext; this.IsNamespaceContext = isNamespaceContext; this.IsNamespaceDeclarationNameContext = isNamespaceDeclarationNameContext; this.IsPreProcessorDirectiveContext = isPreProcessorDirectiveContext; this.IsPreProcessorExpressionContext = isPreProcessorExpressionContext; this.IsRightOfNameSeparator = isRightOfNameSeparator; this.IsStatementContext = isStatementContext; this.IsAnyExpressionContext = isAnyExpressionContext; this.IsAttributeNameContext = isAttributeNameContext; this.IsEnumTypeMemberAccessContext = isEnumTypeMemberAccessContext; this.IsNameOfContext = isNameOfContext; this.IsInQuery = isInQuery; this.IsInImportsDirective = isInImportsDirective; this.IsWithinAsyncMethod = isWithinAsyncMethod; this.IsPossibleTupleContext = isPossibleTupleContext; this.IsAtStartOfPattern = isAtStartOfPattern; this.IsAtEndOfPattern = isAtEndOfPattern; this.InferredTypes = ComputeInferredTypes(workspace, semanticModel, position, cancellationToken); this.IsRightSideOfNumericType = isRightSideOfNumericType; this.IsOnArgumentListBracketOrComma = isOnArgumentListBracketOrComma; } public Workspace Workspace { get; } public SemanticModel SemanticModel { get; } public SyntaxTree SyntaxTree { get; } public int Position { get; } /// <summary> /// The token to the left of <see cref="Position"/>. This token may be touching the position. /// </summary> public SyntaxToken LeftToken { get; } /// <summary> /// The first token to the left of <see cref="Position"/> that we're not touching. Equal to <see cref="LeftToken"/> /// if we aren't touching <see cref="LeftToken" />. /// </summary> public SyntaxToken TargetToken { get; } public bool IsTypeContext { get; } public bool IsNamespaceContext { get; } public bool IsNamespaceDeclarationNameContext { get; } public bool IsPreProcessorDirectiveContext { get; } public bool IsPreProcessorExpressionContext { get; } public bool IsRightOfNameSeparator { get; } public bool IsStatementContext { get; } public bool IsAnyExpressionContext { get; } public bool IsAttributeNameContext { get; } public bool IsEnumTypeMemberAccessContext { get; } public bool IsNameOfContext { get; } public bool IsInQuery { get; } public bool IsInImportsDirective { get; } public bool IsWithinAsyncMethod { get; } public bool IsPossibleTupleContext { get; } public bool IsAtStartOfPattern { get; } public bool IsAtEndOfPattern { get; } public bool IsRightSideOfNumericType { get; } public bool IsOnArgumentListBracketOrComma { get; } public ImmutableArray<ITypeSymbol> InferredTypes { get; } private ISet<INamedTypeSymbol> ComputeOuterTypes(CancellationToken cancellationToken) { var enclosingSymbol = this.SemanticModel.GetEnclosingSymbol(this.LeftToken.SpanStart, cancellationToken); if (enclosingSymbol != null) { var containingType = enclosingSymbol.GetContainingTypeOrThis(); if (containingType != null) { return containingType.GetContainingTypes().ToSet(); } } return SpecializedCollections.EmptySet<INamedTypeSymbol>(); } protected ImmutableArray<ITypeSymbol> ComputeInferredTypes(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var typeInferenceService = workspace?.Services.GetLanguageService<ITypeInferenceService>(semanticModel.Language) ?? GetTypeInferenceServiceWithoutWorkspace(); return typeInferenceService.InferTypes(semanticModel, position, cancellationToken); } internal abstract ITypeInferenceService GetTypeInferenceServiceWithoutWorkspace(); internal abstract bool IsAwaitKeywordContext(); public ISet<INamedTypeSymbol> GetOuterTypes(CancellationToken cancellationToken) { if (_outerTypes == null) { Interlocked.CompareExchange(ref _outerTypes, ComputeOuterTypes(cancellationToken), null); } return _outerTypes; } public TService GetLanguageService<TService>() where TService : class, ILanguageService => this.Workspace.Services.GetLanguageService<TService>(this.SemanticModel.Language); public TService GetWorkspaceService<TService>() where TService : class, IWorkspaceService => this.Workspace.Services.GetService<TService>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery { internal abstract class SyntaxContext { private ISet<INamedTypeSymbol> _outerTypes; protected SyntaxContext( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken leftToken, SyntaxToken targetToken, bool isTypeContext, bool isNamespaceContext, bool isNamespaceDeclarationNameContext, bool isPreProcessorDirectiveContext, bool isPreProcessorExpressionContext, bool isRightOfNameSeparator, bool isStatementContext, bool isAnyExpressionContext, bool isAttributeNameContext, bool isEnumTypeMemberAccessContext, bool isNameOfContext, bool isInQuery, bool isInImportsDirective, bool isWithinAsyncMethod, bool isPossibleTupleContext, bool isAtStartOfPattern, bool isAtEndOfPattern, bool isRightSideOfNumericType, bool isOnArgumentListBracketOrComma, CancellationToken cancellationToken) { this.Workspace = workspace; this.SemanticModel = semanticModel; this.SyntaxTree = semanticModel.SyntaxTree; this.Position = position; this.LeftToken = leftToken; this.TargetToken = targetToken; this.IsTypeContext = isTypeContext; this.IsNamespaceContext = isNamespaceContext; this.IsNamespaceDeclarationNameContext = isNamespaceDeclarationNameContext; this.IsPreProcessorDirectiveContext = isPreProcessorDirectiveContext; this.IsPreProcessorExpressionContext = isPreProcessorExpressionContext; this.IsRightOfNameSeparator = isRightOfNameSeparator; this.IsStatementContext = isStatementContext; this.IsAnyExpressionContext = isAnyExpressionContext; this.IsAttributeNameContext = isAttributeNameContext; this.IsEnumTypeMemberAccessContext = isEnumTypeMemberAccessContext; this.IsNameOfContext = isNameOfContext; this.IsInQuery = isInQuery; this.IsInImportsDirective = isInImportsDirective; this.IsWithinAsyncMethod = isWithinAsyncMethod; this.IsPossibleTupleContext = isPossibleTupleContext; this.IsAtStartOfPattern = isAtStartOfPattern; this.IsAtEndOfPattern = isAtEndOfPattern; this.InferredTypes = ComputeInferredTypes(workspace, semanticModel, position, cancellationToken); this.IsRightSideOfNumericType = isRightSideOfNumericType; this.IsOnArgumentListBracketOrComma = isOnArgumentListBracketOrComma; } public Workspace Workspace { get; } public SemanticModel SemanticModel { get; } public SyntaxTree SyntaxTree { get; } public int Position { get; } /// <summary> /// The token to the left of <see cref="Position"/>. This token may be touching the position. /// </summary> public SyntaxToken LeftToken { get; } /// <summary> /// The first token to the left of <see cref="Position"/> that we're not touching. Equal to <see cref="LeftToken"/> /// if we aren't touching <see cref="LeftToken" />. /// </summary> public SyntaxToken TargetToken { get; } public bool IsTypeContext { get; } public bool IsNamespaceContext { get; } public bool IsNamespaceDeclarationNameContext { get; } public bool IsPreProcessorDirectiveContext { get; } public bool IsPreProcessorExpressionContext { get; } public bool IsRightOfNameSeparator { get; } public bool IsStatementContext { get; } public bool IsAnyExpressionContext { get; } public bool IsAttributeNameContext { get; } public bool IsEnumTypeMemberAccessContext { get; } public bool IsNameOfContext { get; } public bool IsInQuery { get; } public bool IsInImportsDirective { get; } public bool IsWithinAsyncMethod { get; } public bool IsPossibleTupleContext { get; } public bool IsAtStartOfPattern { get; } public bool IsAtEndOfPattern { get; } public bool IsRightSideOfNumericType { get; } public bool IsOnArgumentListBracketOrComma { get; } public ImmutableArray<ITypeSymbol> InferredTypes { get; } private ISet<INamedTypeSymbol> ComputeOuterTypes(CancellationToken cancellationToken) { var enclosingSymbol = this.SemanticModel.GetEnclosingSymbol(this.LeftToken.SpanStart, cancellationToken); if (enclosingSymbol != null) { var containingType = enclosingSymbol.GetContainingTypeOrThis(); if (containingType != null) { return containingType.GetContainingTypes().ToSet(); } } return SpecializedCollections.EmptySet<INamedTypeSymbol>(); } protected ImmutableArray<ITypeSymbol> ComputeInferredTypes(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var typeInferenceService = workspace?.Services.GetLanguageService<ITypeInferenceService>(semanticModel.Language) ?? GetTypeInferenceServiceWithoutWorkspace(); return typeInferenceService.InferTypes(semanticModel, position, cancellationToken); } internal abstract ITypeInferenceService GetTypeInferenceServiceWithoutWorkspace(); internal abstract bool IsAwaitKeywordContext(); public ISet<INamedTypeSymbol> GetOuterTypes(CancellationToken cancellationToken) { if (_outerTypes == null) { Interlocked.CompareExchange(ref _outerTypes, ComputeOuterTypes(cancellationToken), null); } return _outerTypes; } public TService GetLanguageService<TService>() where TService : class, ILanguageService => this.Workspace.Services.GetLanguageService<TService>(this.SemanticModel.Language); public TService GetWorkspaceService<TService>() where TService : class, IWorkspaceService => this.Workspace.Services.GetService<TService>(); } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.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 Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim <ExportLanguageService(GetType(IEntryPointFinderService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEntryPointFinderService Implements IEntryPointFinderService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function FindEntryPoints(symbol As INamespaceSymbol, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) Implements IEntryPointFinderService.FindEntryPoints Return EntryPointFinder.FindEntryPoints(symbol, findFormsOnly) 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.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim <ExportLanguageService(GetType(IEntryPointFinderService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEntryPointFinderService Implements IEntryPointFinderService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function FindEntryPoints(symbol As INamespaceSymbol, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) Implements IEntryPointFinderService.FindEntryPoints Return EntryPointFinder.FindEntryPoints(symbol, findFormsOnly) End Function End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/TestUtilities2/Utilities/GoToHelpers/MockDocumentNavigationServiceFactory.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 Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Navigation Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers <ExportWorkspaceServiceFactory(GetType(IDocumentNavigationService), ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class MockDocumentNavigationServiceFactory Implements IWorkspaceServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateService(workspaceServices As HostWorkspaceServices) As IWorkspaceService Implements IWorkspaceServiceFactory.CreateService Return New MockDocumentNavigationService() 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.Composition Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Navigation Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers <ExportWorkspaceServiceFactory(GetType(IDocumentNavigationService), ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class MockDocumentNavigationServiceFactory Implements IWorkspaceServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateService(workspaceServices As HostWorkspaceServices) As IWorkspaceService Implements IWorkspaceServiceFactory.CreateService Return New MockDocumentNavigationService() End Function End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Features/Core/Portable/UnusedReferences/UpdateAction.cs
// Licensed to the .NET Foundation under one or more 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.UnusedReferences { internal enum UpdateAction { /// <summary> /// No action needs to be performed. /// </summary> None, /// <summary> /// Indicates the reference should be marked as used. /// </summary> TreatAsUsed, /// <summary> /// Indicates the reference should be marked as unused /// </summary> TreatAsUnused, /// <summary> /// Indicates the reference should be removed from the project. /// </summary> Remove, } }
// Licensed to the .NET Foundation under one or more 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.UnusedReferences { internal enum UpdateAction { /// <summary> /// No action needs to be performed. /// </summary> None, /// <summary> /// Indicates the reference should be marked as used. /// </summary> TreatAsUsed, /// <summary> /// Indicates the reference should be marked as unused /// </summary> TreatAsUnused, /// <summary> /// Indicates the reference should be removed from the project. /// </summary> Remove, } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.Expander.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.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Private Class Expander Inherits VisualBasicSyntaxRewriter Private ReadOnly _semanticModel As SemanticModel Private ReadOnly _expandInsideNode As Func(Of SyntaxNode, Boolean) Private ReadOnly _expandParameter As Boolean Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _annotationForReplacedAliasIdentifier As SyntaxAnnotation Public Sub New( semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken, Optional expandParameter As Boolean = False, Optional aliasReplacementAnnotation As SyntaxAnnotation = Nothing) MyBase.New(visitIntoStructuredTrivia:=True) _semanticModel = semanticModel _expandInsideNode = expandInsideNode _cancellationToken = cancellationToken _expandParameter = expandParameter _annotationForReplacedAliasIdentifier = aliasReplacementAnnotation End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If _expandInsideNode Is Nothing OrElse _expandInsideNode(node) Then Return MyBase.Visit(node) End If Return node End Function Private Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim semanticModel = _semanticModel If expression.SyntaxTree IsNot oldExpression.SyntaxTree Then Dim specAnalyzer = New SpeculationAnalyzer(oldExpression, expression, _semanticModel, _cancellationToken) semanticModel = specAnalyzer.SpeculativeSemanticModel If semanticModel Is Nothing Then Return expression End If expression = specAnalyzer.ReplacedExpression End If Return AddCast(expression, targetType, semanticModel) End Function Private Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, semanticModel As SemanticModel) As ExpressionSyntax Dim wasCastAdded As Boolean = False Dim result = expression.CastIfPossible(targetType, expression.SpanStart, semanticModel, wasCastAdded, _cancellationToken) If wasCastAdded Then result = result.Parenthesize() End If Return result End Function Private Function AddCasts(expression As ExpressionSyntax, typeInfo As TypeInfo, conversion As Conversion, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim result = expression If typeInfo.Type IsNot Nothing AndAlso typeInfo.Type.IsAnonymousDelegateType() AndAlso conversion.IsUserDefined AndAlso conversion.IsWidening AndAlso conversion.MethodSymbol IsNot Nothing AndAlso conversion.MethodSymbol.Parameters.Length > 0 Then Dim conversionType = conversion.MethodSymbol.Parameters(0).Type If conversionType IsNot Nothing Then result = AddCast(result, conversionType, oldExpression) End If End If If typeInfo.ConvertedType IsNot Nothing Then result = AddCast(result, typeInfo.ConvertedType, oldExpression) End If ' If we didn't add a cast, at least parenthesize the expression. If result Is expression Then result = result.Parenthesize() End If Return result End Function Public Overrides Function VisitParameter(node As ParameterSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitParameter(node), ParameterSyntax) If newNode IsNot Nothing AndAlso newNode.AsClause Is Nothing AndAlso _expandParameter Then Dim newNodeSymbol = _semanticModel.GetDeclaredSymbol(node) If newNodeSymbol IsNot Nothing AndAlso newNodeSymbol.Kind = SymbolKind.Parameter Then Dim symbolType = newNodeSymbol.Type If symbolType IsNot Nothing Then Dim typeSyntax = symbolType.GenerateTypeSyntax(True) Dim asClause = SyntaxFactory.SimpleAsClause(typeSyntax).NormalizeWhitespace() If newNode.Default Is Nothing Then Dim newAsClause = asClause.WithTrailingTrivia(newNode.Identifier.GetTrailingTrivia()) Dim newIdentifier = newNode.Identifier.WithTrailingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newIdentifier, newAsClause, newNode.Default) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newNode.Identifier, asClause, newNode.Default).WithAdditionalAnnotations(Simplifier.Annotation) End If End If End If Return newNode End Function Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newAssignment = DirectCast(MyBase.VisitAssignmentStatement(node), AssignmentStatementSyntax) Dim typeInfo = _semanticModel.GetTypeInfo(node.Right) Dim conversion = _semanticModel.GetConversion(node.Right) Dim newExpression = AddCasts(newAssignment.Right, typeInfo, conversion, node.Right) newAssignment = newAssignment _ .WithRight(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newAssignment End Function Public Overrides Function VisitExpressionStatement(node As ExpressionStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newExpressionStatement = DirectCast(MyBase.VisitExpressionStatement(node), ExpressionStatementSyntax) If newExpressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then ' move all leading trivia before the call keyword Dim leadingTrivia = newExpressionStatement.GetLeadingTrivia() newExpressionStatement = newExpressionStatement.WithLeadingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Dim callStatement = SyntaxFactory.CallStatement(newExpressionStatement.Expression) _ .WithLeadingTrivia(leadingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) ' copy over annotations, if any. callStatement = newExpressionStatement.CopyAnnotationsTo(callStatement) Return callStatement End If Return newExpressionStatement End Function Public Overrides Function VisitEqualsValue(node As EqualsValueSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newEqualsValue = DirectCast(MyBase.VisitEqualsValue(node), EqualsValueSyntax) If node.Value IsNot Nothing AndAlso Not node.Value.IsMissing AndAlso newEqualsValue.Value IsNot Nothing AndAlso Not newEqualsValue.IsMissing Then Dim typeInfo = _semanticModel.GetTypeInfo(node.Value) Dim conversion = _semanticModel.GetConversion(node.Value) Dim newValue = AddCasts(newEqualsValue.Value, typeInfo, conversion, node.Value) newEqualsValue = newEqualsValue _ .WithValue(newValue) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newEqualsValue End Function Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newInvocationExpression = DirectCast(MyBase.VisitInvocationExpression(node), InvocationExpressionSyntax) ' the argument for redim needs to be an LValue and therefore cannot be a cast or parenthesized expression. If node.IsParentKind(SyntaxKind.ReDimKeyword) Then Return newInvocationExpression End If If newInvocationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newInvocationExpression.GetTrailingTrivia() newInvocationExpression = newInvocationExpression _ .WithTrailingTrivia(SyntaxTriviaList.Empty) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If If node.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim memberAccess = DirectCast(node.Expression, MemberAccessExpressionSyntax) Dim targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name) If Not targetSymbol Is Nothing And targetSymbol.IsReducedExtension() AndAlso memberAccess.Expression IsNot Nothing Then newInvocationExpression = RewriteExtensionMethodInvocation(node, newInvocationExpression, memberAccess.Expression, DirectCast(newInvocationExpression.Expression, MemberAccessExpressionSyntax).Expression, DirectCast(targetSymbol, IMethodSymbol)) End If End If Return newInvocationExpression End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, rewrittenNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol) As InvocationExpressionSyntax Dim originalMemberAccess = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax) If originalMemberAccess.GetRootConditionalAccessExpression() IsNot Nothing Then ' Bail out on extension method invocations in conditional access expression. ' Note that this is a temporary workaround for https://github.com/dotnet/roslyn/issues/2593. ' Issue https//github.com/dotnet/roslyn/issues/3260 tracks fixing this workaround. Return rewrittenNode End If Dim expression = RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithoutGenerics) Dim binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression) If (Not binding.Symbol Is Nothing) Then Return expression End If ' The previous binding did not work. So we are going to include the type arguments as well Return RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithGenerics) End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol, symbolDisplayFormat As SymbolDisplayFormat) As InvocationExpressionSyntax Dim containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat) Dim oldMemberAccess = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax) Dim newMemberAccess = SyntaxFactory.SimpleMemberAccessExpression(SyntaxFactory.ParseExpression(containingType), oldMemberAccess.OperatorToken, oldMemberAccess.Name).WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia) ' Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation) Dim typeInfo = _semanticModel.GetTypeInfo(oldThisExpression) Dim conversion = _semanticModel.GetConversion(oldThisExpression) Dim castedThisExpression = AddCasts(thisExpression, typeInfo, conversion, oldThisExpression) Dim thisArgument = SyntaxFactory.SimpleArgument(castedThisExpression) _ .WithLeadingTrivia(SyntaxTriviaList.Empty) _ .WithAdditionalAnnotations(Simplifier.Annotation) thisArgument = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax).Expression.CopyAnnotationsTo(thisArgument) Dim arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument) Dim replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)) Return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function VisitObjectCreationExpression(node As ObjectCreationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newObjectCreationExpression = DirectCast(MyBase.VisitObjectCreationExpression(node), ObjectCreationExpressionSyntax) If newObjectCreationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newObjectCreationExpression.Type.GetTrailingTrivia() newObjectCreationExpression = newObjectCreationExpression _ .WithType(newObjectCreationExpression.Type.WithTrailingTrivia(SyntaxTriviaList.Empty)) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newObjectCreationExpression End Function Public Overrides Function VisitSimpleArgument(node As SimpleArgumentSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newSimpleArgument = DirectCast(MyBase.VisitSimpleArgument(node), SimpleArgumentSyntax) If node.NameColonEquals Is Nothing Then Dim tuple = TryCast(node.Parent, TupleExpressionSyntax) If tuple IsNot Nothing Then Dim inferredName = node.Expression.TryGetInferredMemberName() If CanMakeNameExplicitInTuple(tuple, inferredName) Then Dim identifier = SyntaxFactory.Identifier(inferredName) identifier = TryEscapeIdentifierToken(identifier) newSimpleArgument = newSimpleArgument. WithLeadingTrivia(). WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(identifier))). WithAdditionalAnnotations(Simplifier.Annotation). WithLeadingTrivia(node.GetLeadingTrivia()) End If End If End If ' We need to be careful here. if this is a local, field or property passed to a ByRef argument, we shouldn't ' parenthesize to avoid breaking copy-back semantics. Dim symbol = _semanticModel.GetSymbolInfo(node.Expression, _cancellationToken).Symbol If symbol IsNot Nothing Then If symbol.MatchesKind(SymbolKind.Local, SymbolKind.Field, SymbolKind.Property) Then Dim parameter = node.DetermineParameter(_semanticModel, cancellationToken:=_cancellationToken) If parameter IsNot Nothing AndAlso parameter.RefKind <> RefKind.None Then Return newSimpleArgument End If End If End If If newSimpleArgument.Expression.Kind = SyntaxKind.AddressOfExpression Then Return newSimpleArgument End If Dim typeInfo = _semanticModel.GetTypeInfo(node.Expression) Dim conversion = _semanticModel.GetConversion(node.Expression) Dim newExpression = AddCasts(newSimpleArgument.Expression, typeInfo, conversion, node.Expression) newSimpleArgument = newSimpleArgument _ .WithExpression(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newSimpleArgument End Function Private Shared Function CanMakeNameExplicitInTuple(tuple As TupleExpressionSyntax, name As String) As Boolean If name Is Nothing OrElse SyntaxFacts.IsReservedTupleElementName(name) Then Return False End If Dim found = False For Each argument In tuple.Arguments Dim elementName As Object If argument.NameColonEquals IsNot Nothing Then elementName = argument.NameColonEquals.Name.Identifier.ValueText Else elementName = argument.Expression?.TryGetInferredMemberName() End If If CaseInsensitiveComparison.Equals(elementName, name) Then If found Then ' No duplicate names allowed Return False End If found = True End If Next Return True End Function Public Overrides Function VisitInferredFieldInitializer(node As InferredFieldInitializerSyntax) As SyntaxNode Dim newInitializer = TryCast(MyBase.VisitInferredFieldInitializer(node), InferredFieldInitializerSyntax) If newInitializer IsNot Nothing Then Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName IsNot Nothing Then Dim identifier = SyntaxFactory.Identifier(inferredName) identifier = TryEscapeIdentifierToken(identifier) Return SyntaxFactory.NamedFieldInitializer(SyntaxFactory.IdentifierName(identifier), newInitializer.Expression.WithoutLeadingTrivia()). WithLeadingTrivia(node.GetLeadingTrivia()). WithAdditionalAnnotations(Simplifier.Annotation) End If End If Return newInitializer End Function Public Overrides Function VisitGenericName(node As GenericNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitGenericName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim baseSingleLineLambda = DirectCast(MyBase.VisitSingleLineLambdaExpression(node), SingleLineLambdaExpressionSyntax) Dim newSingleLineLambda = baseSingleLineLambda _ .Parenthesize() Return newSingleLineLambda End Function Public Overrides Function VisitQualifiedName(node As QualifiedNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenQualifiedName = MyBase.VisitQualifiedName(node) Dim symbolForQualifiedName = _semanticModel.GetSymbolInfo(node).Symbol If symbolForQualifiedName.IsConstructor Then symbolForQualifiedName = symbolForQualifiedName.ContainingSymbol End If If symbolForQualifiedName.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Left).Symbol If Not symbolForQualifiedName.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForQualifiedName.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken) Dim qualifiedNameWithModuleName = rewrittenQualifiedName.CopyAnnotationsTo(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Left, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Right)) If symbolForQualifiedName.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, qualifiedNameWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenQualifiedName = qualifiedNameWithModuleName End If End If End If Return rewrittenQualifiedName End Function Public Overrides Function VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenMemberAccess = MyBase.VisitMemberAccessExpression(node) Dim symbolForMemberAccess = _semanticModel.GetSymbolInfo(node).Symbol If node.Expression IsNot Nothing AndAlso symbolForMemberAccess.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Expression).Symbol If Not symbolForMemberAccess.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForMemberAccess.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken) Dim memberAccessWithModuleName = rewrittenMemberAccess.CopyAnnotationsTo( SyntaxFactory.SimpleMemberAccessExpression( SyntaxFactory.SimpleMemberAccessExpression( DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Expression, node.OperatorToken, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), node.OperatorToken, DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Name)) If symbolForMemberAccess.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, memberAccessWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenMemberAccess = memberAccessWithModuleName End If End If End If Return rewrittenMemberAccess End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitIdentifierName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Private Function VisitSimpleName(rewrittenSimpleName As SimpleNameSyntax, originalSimpleName As SimpleNameSyntax) As ExpressionSyntax _cancellationToken.ThrowIfCancellationRequested() Dim identifier = rewrittenSimpleName.Identifier Dim newNode As ExpressionSyntax = rewrittenSimpleName ' ' 1. if this identifier is an alias, we'll expand it here and replace the node completely. ' If originalSimpleName.Kind = SyntaxKind.IdentifierName Then Dim aliasInfo = _semanticModel.GetAliasInfo(DirectCast(originalSimpleName, IdentifierNameSyntax)) If aliasInfo IsNot Nothing Then Dim aliasTarget = aliasInfo.Target If aliasTarget.IsNamespace() AndAlso DirectCast(aliasTarget, INamespaceSymbol).IsGlobalNamespace Then Return rewrittenSimpleName End If ' if the enclosing expression is a typeof expression that already contains open type we cannot ' we need to insert an open type as well. Dim typeOfExpression = originalSimpleName.GetAncestor(Of TypeOfExpressionSyntax)() If typeOfExpression IsNot Nothing AndAlso IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression) Then aliasTarget = DirectCast(aliasTarget, INamedTypeSymbol).ConstructUnboundGenericType() End If ' the expanded form replaces the current identifier name. Dim replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode:=True) _ .WithAdditionalAnnotations(Simplifier.Annotation) If replacement.Kind = SyntaxKind.QualifiedName Then Dim qualifiedReplacement = DirectCast(replacement, QualifiedNameSyntax) Dim newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Right.Identifier) If Me._annotationForReplacedAliasIdentifier IsNot Nothing Then newIdentifier = newIdentifier.WithAdditionalAnnotations(Me._annotationForReplacedAliasIdentifier) End If Dim aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name) newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo) replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier(newIdentifier)) replacement = newNode.CopyAnnotationsTo(replacement) Return replacement End If If replacement.IsKind(SyntaxKind.IdentifierName) Then Dim identifierReplacement = DirectCast(replacement, IdentifierNameSyntax) Dim newIdentifier = identifier.CopyAnnotationsTo(identifierReplacement.Identifier) If Me._annotationForReplacedAliasIdentifier IsNot Nothing Then newIdentifier = newIdentifier.WithAdditionalAnnotations(Me._annotationForReplacedAliasIdentifier) End If Dim aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name) newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo) replacement = replacement.ReplaceToken(identifier, newIdentifier) replacement = newNode.CopyAnnotationsTo(replacement) Return replacement End If Throw New NotImplementedException() End If End If Dim symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol If symbol Is Nothing Then Return newNode End If ' ' 2. If it's an attribute, make sure the identifier matches the attribute's class name without the attribute suffix. ' If originalSimpleName.GetAncestor(Of AttributeSyntax)() IsNot Nothing Then If symbol.IsConstructor() AndAlso symbol.ContainingType?.IsAttribute() Then symbol = symbol.ContainingType Dim name = symbol.Name Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText, StringComparison.Ordinal)) ' Note, VB can't escape attribute names like C#, so we actually need to expand to the symbol name ' without a suffix, see http://msdn.microsoft.com/en-us/library/aa711866(v=vs.71).aspx Dim newName = String.Empty If name.TryGetWithoutAttributeSuffix(isCaseSensitive:=False, result:=newName) Then If identifier.ValueText <> newName Then identifier = If(identifier.IsBracketed(), identifier.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia)), identifier.CopyAnnotationsTo(SyntaxFactory.Identifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia))) End If ' if the user already used the Attribute suffix in the attribute, we'll maintain it. If identifier.ValueText = name Then identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) End If End If End If End If ' ' 3. Always try to escape keyword identifiers ' identifier = TryEscapeIdentifierToken(identifier) If identifier <> rewrittenSimpleName.Identifier Then Select Case newNode.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName newNode = DirectCast(newNode, SimpleNameSyntax).WithIdentifier(identifier).WithAdditionalAnnotations(Simplifier.Annotation) Case Else Throw New NotImplementedException() End Select End If Dim parent = originalSimpleName.Parent ' do not complexify further for location where only simple names are allowed If (TypeOf (parent) Is FieldInitializerSyntax) OrElse ((TypeOf (parent) Is DeclarationStatementSyntax) AndAlso Not TypeOf (parent) Is InheritsOrImplementsStatementSyntax) OrElse (TypeOf (parent) Is MemberAccessExpressionSyntax AndAlso parent.Kind <> SyntaxKind.SimpleMemberAccessExpression) OrElse (parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso originalSimpleName.IsRightSideOfDot()) OrElse (parent.Kind = SyntaxKind.QualifiedName AndAlso originalSimpleName.IsRightSideOfQualifiedName()) Then Return TryAddTypeArgumentToIdentifierName(newNode, symbol) End If ' ' 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it ' ' we need to treat the constructor as type name, so just get the containing type. If symbol.IsConstructor() AndAlso parent.Kind = SyntaxKind.ObjectCreationExpression Then symbol = symbol.ContainingType End If ' if it's a namespace or type name, fully qualify it. If symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Namespace Then Return FullyQualifyIdentifierName( DirectCast(symbol, INamespaceOrTypeSymbol), newNode, originalSimpleName, replaceNode:=False) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If ' if it's a member access, we're fully qualifying the left side and make it a member access. If symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Field OrElse symbol.Kind = SymbolKind.Property Then If symbol.IsStatic OrElse (TypeOf (parent) Is CrefReferenceSyntax) OrElse _semanticModel.SyntaxTree.IsNameOfContext(originalSimpleName.SpanStart, _cancellationToken) Then newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode:=False) Else Dim left As ExpressionSyntax If Not Equals(_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken), symbol.ContainingType) Then left = SyntaxFactory.MyBaseExpression() Else left = SyntaxFactory.MeExpression() End If Dim identifiersLeadingTrivia = newNode.GetLeadingTrivia() newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol) newNode = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(newNode, SimpleNameSyntax).WithoutLeadingTrivia()) _ .WithLeadingTrivia(identifiersLeadingTrivia) End If newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation) End If Return newNode End Function Private Shared Function TryAddTypeArgumentToIdentifierName( newNode As ExpressionSyntax, symbol As ISymbol) As ExpressionSyntax If newNode.Kind = SyntaxKind.IdentifierName AndAlso symbol.Kind = SymbolKind.Method Then If DirectCast(symbol, IMethodSymbol).TypeArguments.Length <> 0 Then Dim typeArguments = DirectCast(symbol, IMethodSymbol).TypeArguments Dim genericName = SyntaxFactory.GenericName( DirectCast(newNode, IdentifierNameSyntax).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Select(Function(p) SyntaxFactory.ParseTypeName(p.ToDisplayParts(typeNameFormatWithGenerics).ToDisplayString()))))) _ .WithLeadingTrivia(newNode.GetLeadingTrivia()) _ .WithTrailingTrivia(newNode.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Simplifier.Annotation) genericName = newNode.CopyAnnotationsTo(genericName) Return genericName End If End If Return newNode End Function Private Function FullyQualifyIdentifierName( symbol As ISymbol, rewrittenNode As ExpressionSyntax, originalNode As ExpressionSyntax, replaceNode As Boolean ) As ExpressionSyntax Debug.Assert(Not replaceNode OrElse rewrittenNode.Kind = SyntaxKind.IdentifierName) ' TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. ' See GenerateExpressionSyntax(); Dim result = rewrittenNode ' only if this symbol has a containing type or namespace there is work for us to do. If replaceNode OrElse symbol.ContainingType IsNot Nothing OrElse symbol.ContainingNamespace IsNot Nothing Then Dim symbolForQualification = If(replaceNode, symbol, symbol.ContainingSymbol) rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol) Dim displayParts = symbolForQualification.ToDisplayParts(typeNameFormatWithGenerics) Dim left As ExpressionSyntax = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) ' symbol display always includes module names in the qualification, but this can sometimes break code ' (see bug 529837). ' if we don't get back the same symbol for the full qualification, then we'll omit the module name. If symbol.IsModuleMember Then Dim newSymbol = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, left, SpeculativeBindingOption.BindAsExpression).Symbol If Not symbolForQualification.Equals(newSymbol) Then displayParts = symbolForQualification.ContainingSymbol.ToDisplayParts(typeNameFormatWithGenerics) left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) End If End If If replaceNode Then result = left _ .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) _ .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()) Debug.Assert( symbol.Equals(_semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, result, SpeculativeBindingOption.BindAsExpression).Symbol)) Return result End If ' now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier Dim parent = originalNode.Parent Dim leadingTrivia = rewrittenNode.GetLeadingTrivia() rewrittenNode = rewrittenNode.WithoutLeadingTrivia() Select Case parent.Kind Case SyntaxKind.QualifiedName result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( DirectCast(left, NameSyntax), DirectCast(rewrittenNode, SimpleNameSyntax))) Case SyntaxKind.SimpleMemberAccessExpression Dim memberAccessParent = DirectCast(parent, MemberAccessExpressionSyntax) result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, memberAccessParent.OperatorToken, DirectCast(rewrittenNode, SimpleNameSyntax))) Case Else Debug.Assert(TypeOf (rewrittenNode) Is SimpleNameSyntax) If SyntaxFacts.IsInNamespaceOrTypeContext(originalNode) OrElse TypeOf (parent) Is CrefReferenceSyntax Then Dim right = DirectCast(rewrittenNode, SimpleNameSyntax) result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))) Else result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(rewrittenNode, SimpleNameSyntax))) End If End Select result = result.WithLeadingTrivia(leadingTrivia) End If Return result End Function Private Function IsTypeOfUnboundGenericType(semanticModel As SemanticModel, typeOfExpression As TypeOfExpressionSyntax) As Boolean If typeOfExpression IsNot Nothing Then Dim type = TryCast(semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type, INamedTypeSymbol) ' It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through ' parent types too Do While type IsNot Nothing If type.IsUnboundGenericType Then Return True End If type = type.ContainingType Loop End If Return False End Function Public Overrides Function VisitLabelStatement(node As LabelStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newLabelStatement = DirectCast(MyBase.VisitLabelStatement(node), LabelStatementSyntax) Dim escapedLabelToken = TryEscapeIdentifierToken(newLabelStatement.LabelToken) If newLabelStatement.LabelToken <> escapedLabelToken Then newLabelStatement = newLabelStatement.WithLabelToken(escapedLabelToken) End If Return newLabelStatement End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicSimplificationService Private Class Expander Inherits VisualBasicSyntaxRewriter Private ReadOnly _semanticModel As SemanticModel Private ReadOnly _expandInsideNode As Func(Of SyntaxNode, Boolean) Private ReadOnly _expandParameter As Boolean Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _annotationForReplacedAliasIdentifier As SyntaxAnnotation Public Sub New( semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken, Optional expandParameter As Boolean = False, Optional aliasReplacementAnnotation As SyntaxAnnotation = Nothing) MyBase.New(visitIntoStructuredTrivia:=True) _semanticModel = semanticModel _expandInsideNode = expandInsideNode _cancellationToken = cancellationToken _expandParameter = expandParameter _annotationForReplacedAliasIdentifier = aliasReplacementAnnotation End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode If _expandInsideNode Is Nothing OrElse _expandInsideNode(node) Then Return MyBase.Visit(node) End If Return node End Function Private Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim semanticModel = _semanticModel If expression.SyntaxTree IsNot oldExpression.SyntaxTree Then Dim specAnalyzer = New SpeculationAnalyzer(oldExpression, expression, _semanticModel, _cancellationToken) semanticModel = specAnalyzer.SpeculativeSemanticModel If semanticModel Is Nothing Then Return expression End If expression = specAnalyzer.ReplacedExpression End If Return AddCast(expression, targetType, semanticModel) End Function Private Function AddCast(expression As ExpressionSyntax, targetType As ITypeSymbol, semanticModel As SemanticModel) As ExpressionSyntax Dim wasCastAdded As Boolean = False Dim result = expression.CastIfPossible(targetType, expression.SpanStart, semanticModel, wasCastAdded, _cancellationToken) If wasCastAdded Then result = result.Parenthesize() End If Return result End Function Private Function AddCasts(expression As ExpressionSyntax, typeInfo As TypeInfo, conversion As Conversion, oldExpression As ExpressionSyntax) As ExpressionSyntax Dim result = expression If typeInfo.Type IsNot Nothing AndAlso typeInfo.Type.IsAnonymousDelegateType() AndAlso conversion.IsUserDefined AndAlso conversion.IsWidening AndAlso conversion.MethodSymbol IsNot Nothing AndAlso conversion.MethodSymbol.Parameters.Length > 0 Then Dim conversionType = conversion.MethodSymbol.Parameters(0).Type If conversionType IsNot Nothing Then result = AddCast(result, conversionType, oldExpression) End If End If If typeInfo.ConvertedType IsNot Nothing Then result = AddCast(result, typeInfo.ConvertedType, oldExpression) End If ' If we didn't add a cast, at least parenthesize the expression. If result Is expression Then result = result.Parenthesize() End If Return result End Function Public Overrides Function VisitParameter(node As ParameterSyntax) As SyntaxNode Dim newNode = DirectCast(MyBase.VisitParameter(node), ParameterSyntax) If newNode IsNot Nothing AndAlso newNode.AsClause Is Nothing AndAlso _expandParameter Then Dim newNodeSymbol = _semanticModel.GetDeclaredSymbol(node) If newNodeSymbol IsNot Nothing AndAlso newNodeSymbol.Kind = SymbolKind.Parameter Then Dim symbolType = newNodeSymbol.Type If symbolType IsNot Nothing Then Dim typeSyntax = symbolType.GenerateTypeSyntax(True) Dim asClause = SyntaxFactory.SimpleAsClause(typeSyntax).NormalizeWhitespace() If newNode.Default Is Nothing Then Dim newAsClause = asClause.WithTrailingTrivia(newNode.Identifier.GetTrailingTrivia()) Dim newIdentifier = newNode.Identifier.WithTrailingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newIdentifier, newAsClause, newNode.Default) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return SyntaxFactory.Parameter(newNode.AttributeLists, newNode.Modifiers, newNode.Identifier, asClause, newNode.Default).WithAdditionalAnnotations(Simplifier.Annotation) End If End If End If Return newNode End Function Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newAssignment = DirectCast(MyBase.VisitAssignmentStatement(node), AssignmentStatementSyntax) Dim typeInfo = _semanticModel.GetTypeInfo(node.Right) Dim conversion = _semanticModel.GetConversion(node.Right) Dim newExpression = AddCasts(newAssignment.Right, typeInfo, conversion, node.Right) newAssignment = newAssignment _ .WithRight(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newAssignment End Function Public Overrides Function VisitExpressionStatement(node As ExpressionStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newExpressionStatement = DirectCast(MyBase.VisitExpressionStatement(node), ExpressionStatementSyntax) If newExpressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then ' move all leading trivia before the call keyword Dim leadingTrivia = newExpressionStatement.GetLeadingTrivia() newExpressionStatement = newExpressionStatement.WithLeadingTrivia({SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList()) Dim callStatement = SyntaxFactory.CallStatement(newExpressionStatement.Expression) _ .WithLeadingTrivia(leadingTrivia) _ .WithAdditionalAnnotations(Simplifier.Annotation) ' copy over annotations, if any. callStatement = newExpressionStatement.CopyAnnotationsTo(callStatement) Return callStatement End If Return newExpressionStatement End Function Public Overrides Function VisitEqualsValue(node As EqualsValueSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newEqualsValue = DirectCast(MyBase.VisitEqualsValue(node), EqualsValueSyntax) If node.Value IsNot Nothing AndAlso Not node.Value.IsMissing AndAlso newEqualsValue.Value IsNot Nothing AndAlso Not newEqualsValue.IsMissing Then Dim typeInfo = _semanticModel.GetTypeInfo(node.Value) Dim conversion = _semanticModel.GetConversion(node.Value) Dim newValue = AddCasts(newEqualsValue.Value, typeInfo, conversion, node.Value) newEqualsValue = newEqualsValue _ .WithValue(newValue) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newEqualsValue End Function Public Overrides Function VisitInvocationExpression(node As InvocationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newInvocationExpression = DirectCast(MyBase.VisitInvocationExpression(node), InvocationExpressionSyntax) ' the argument for redim needs to be an LValue and therefore cannot be a cast or parenthesized expression. If node.IsParentKind(SyntaxKind.ReDimKeyword) Then Return newInvocationExpression End If If newInvocationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newInvocationExpression.GetTrailingTrivia() newInvocationExpression = newInvocationExpression _ .WithTrailingTrivia(SyntaxTriviaList.Empty) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If If node.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Dim memberAccess = DirectCast(node.Expression, MemberAccessExpressionSyntax) Dim targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name) If Not targetSymbol Is Nothing And targetSymbol.IsReducedExtension() AndAlso memberAccess.Expression IsNot Nothing Then newInvocationExpression = RewriteExtensionMethodInvocation(node, newInvocationExpression, memberAccess.Expression, DirectCast(newInvocationExpression.Expression, MemberAccessExpressionSyntax).Expression, DirectCast(targetSymbol, IMethodSymbol)) End If End If Return newInvocationExpression End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, rewrittenNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol) As InvocationExpressionSyntax Dim originalMemberAccess = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax) If originalMemberAccess.GetRootConditionalAccessExpression() IsNot Nothing Then ' Bail out on extension method invocations in conditional access expression. ' Note that this is a temporary workaround for https://github.com/dotnet/roslyn/issues/2593. ' Issue https//github.com/dotnet/roslyn/issues/3260 tracks fixing this workaround. Return rewrittenNode End If Dim expression = RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithoutGenerics) Dim binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression) If (Not binding.Symbol Is Nothing) Then Return expression End If ' The previous binding did not work. So we are going to include the type arguments as well Return RewriteExtensionMethodInvocation(rewrittenNode, oldThisExpression, thisExpression, reducedExtensionMethod, typeNameFormatWithGenerics) End Function Private Function RewriteExtensionMethodInvocation( originalNode As InvocationExpressionSyntax, oldThisExpression As ExpressionSyntax, thisExpression As ExpressionSyntax, reducedExtensionMethod As IMethodSymbol, symbolDisplayFormat As SymbolDisplayFormat) As InvocationExpressionSyntax Dim containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat) Dim oldMemberAccess = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax) Dim newMemberAccess = SyntaxFactory.SimpleMemberAccessExpression(SyntaxFactory.ParseExpression(containingType), oldMemberAccess.OperatorToken, oldMemberAccess.Name).WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia) ' Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation) Dim typeInfo = _semanticModel.GetTypeInfo(oldThisExpression) Dim conversion = _semanticModel.GetConversion(oldThisExpression) Dim castedThisExpression = AddCasts(thisExpression, typeInfo, conversion, oldThisExpression) Dim thisArgument = SyntaxFactory.SimpleArgument(castedThisExpression) _ .WithLeadingTrivia(SyntaxTriviaList.Empty) _ .WithAdditionalAnnotations(Simplifier.Annotation) thisArgument = DirectCast(originalNode.Expression, MemberAccessExpressionSyntax).Expression.CopyAnnotationsTo(thisArgument) Dim arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument) Dim replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)) Return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Overrides Function VisitObjectCreationExpression(node As ObjectCreationExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newObjectCreationExpression = DirectCast(MyBase.VisitObjectCreationExpression(node), ObjectCreationExpressionSyntax) If newObjectCreationExpression.ArgumentList Is Nothing Then Dim trailingTrivia = newObjectCreationExpression.Type.GetTrailingTrivia() newObjectCreationExpression = newObjectCreationExpression _ .WithType(newObjectCreationExpression.Type.WithTrailingTrivia(SyntaxTriviaList.Empty)) _ .WithArgumentList(SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Return newObjectCreationExpression End Function Public Overrides Function VisitSimpleArgument(node As SimpleArgumentSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newSimpleArgument = DirectCast(MyBase.VisitSimpleArgument(node), SimpleArgumentSyntax) If node.NameColonEquals Is Nothing Then Dim tuple = TryCast(node.Parent, TupleExpressionSyntax) If tuple IsNot Nothing Then Dim inferredName = node.Expression.TryGetInferredMemberName() If CanMakeNameExplicitInTuple(tuple, inferredName) Then Dim identifier = SyntaxFactory.Identifier(inferredName) identifier = TryEscapeIdentifierToken(identifier) newSimpleArgument = newSimpleArgument. WithLeadingTrivia(). WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName(identifier))). WithAdditionalAnnotations(Simplifier.Annotation). WithLeadingTrivia(node.GetLeadingTrivia()) End If End If End If ' We need to be careful here. if this is a local, field or property passed to a ByRef argument, we shouldn't ' parenthesize to avoid breaking copy-back semantics. Dim symbol = _semanticModel.GetSymbolInfo(node.Expression, _cancellationToken).Symbol If symbol IsNot Nothing Then If symbol.MatchesKind(SymbolKind.Local, SymbolKind.Field, SymbolKind.Property) Then Dim parameter = node.DetermineParameter(_semanticModel, cancellationToken:=_cancellationToken) If parameter IsNot Nothing AndAlso parameter.RefKind <> RefKind.None Then Return newSimpleArgument End If End If End If If newSimpleArgument.Expression.Kind = SyntaxKind.AddressOfExpression Then Return newSimpleArgument End If Dim typeInfo = _semanticModel.GetTypeInfo(node.Expression) Dim conversion = _semanticModel.GetConversion(node.Expression) Dim newExpression = AddCasts(newSimpleArgument.Expression, typeInfo, conversion, node.Expression) newSimpleArgument = newSimpleArgument _ .WithExpression(newExpression) _ .WithAdditionalAnnotations(Simplifier.Annotation) Return newSimpleArgument End Function Private Shared Function CanMakeNameExplicitInTuple(tuple As TupleExpressionSyntax, name As String) As Boolean If name Is Nothing OrElse SyntaxFacts.IsReservedTupleElementName(name) Then Return False End If Dim found = False For Each argument In tuple.Arguments Dim elementName As Object If argument.NameColonEquals IsNot Nothing Then elementName = argument.NameColonEquals.Name.Identifier.ValueText Else elementName = argument.Expression?.TryGetInferredMemberName() End If If CaseInsensitiveComparison.Equals(elementName, name) Then If found Then ' No duplicate names allowed Return False End If found = True End If Next Return True End Function Public Overrides Function VisitInferredFieldInitializer(node As InferredFieldInitializerSyntax) As SyntaxNode Dim newInitializer = TryCast(MyBase.VisitInferredFieldInitializer(node), InferredFieldInitializerSyntax) If newInitializer IsNot Nothing Then Dim inferredName = node.Expression.TryGetInferredMemberName() If inferredName IsNot Nothing Then Dim identifier = SyntaxFactory.Identifier(inferredName) identifier = TryEscapeIdentifierToken(identifier) Return SyntaxFactory.NamedFieldInitializer(SyntaxFactory.IdentifierName(identifier), newInitializer.Expression.WithoutLeadingTrivia()). WithLeadingTrivia(node.GetLeadingTrivia()). WithAdditionalAnnotations(Simplifier.Annotation) End If End If Return newInitializer End Function Public Overrides Function VisitGenericName(node As GenericNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitGenericName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim baseSingleLineLambda = DirectCast(MyBase.VisitSingleLineLambdaExpression(node), SingleLineLambdaExpressionSyntax) Dim newSingleLineLambda = baseSingleLineLambda _ .Parenthesize() Return newSingleLineLambda End Function Public Overrides Function VisitQualifiedName(node As QualifiedNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenQualifiedName = MyBase.VisitQualifiedName(node) Dim symbolForQualifiedName = _semanticModel.GetSymbolInfo(node).Symbol If symbolForQualifiedName.IsConstructor Then symbolForQualifiedName = symbolForQualifiedName.ContainingSymbol End If If symbolForQualifiedName.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Left).Symbol If Not symbolForQualifiedName.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForQualifiedName.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken) Dim qualifiedNameWithModuleName = rewrittenQualifiedName.CopyAnnotationsTo(SyntaxFactory.QualifiedName( SyntaxFactory.QualifiedName(DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Left, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), DirectCast(rewrittenQualifiedName, QualifiedNameSyntax).Right)) If symbolForQualifiedName.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, qualifiedNameWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenQualifiedName = qualifiedNameWithModuleName End If End If End If Return rewrittenQualifiedName End Function Public Overrides Function VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim rewrittenMemberAccess = MyBase.VisitMemberAccessExpression(node) Dim symbolForMemberAccess = _semanticModel.GetSymbolInfo(node).Symbol If node.Expression IsNot Nothing AndAlso symbolForMemberAccess.IsModuleMember Then Dim symbolForLeftPart = _semanticModel.GetSymbolInfo(node.Expression).Symbol If Not symbolForMemberAccess.ContainingType.Equals(symbolForLeftPart) Then ' <rewritten_left>.<module_name>.<rewritten_right> Dim moduleIdentifierToken = SyntaxFactory.Identifier(symbolForMemberAccess.ContainingType.Name) moduleIdentifierToken = TryEscapeIdentifierToken(moduleIdentifierToken) Dim memberAccessWithModuleName = rewrittenMemberAccess.CopyAnnotationsTo( SyntaxFactory.SimpleMemberAccessExpression( SyntaxFactory.SimpleMemberAccessExpression( DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Expression, node.OperatorToken, SyntaxFactory.IdentifierName(moduleIdentifierToken)) _ .WithAdditionalAnnotations(Simplifier.Annotation, SimplificationHelpers.SimplifyModuleNameAnnotation), node.OperatorToken, DirectCast(rewrittenMemberAccess, MemberAccessExpressionSyntax).Name)) If symbolForMemberAccess.Equals(_semanticModel.GetSpeculativeSymbolInfo(node.SpanStart, memberAccessWithModuleName, SpeculativeBindingOption.BindAsExpression).Symbol) Then rewrittenMemberAccess = memberAccessWithModuleName End If End If End If Return rewrittenMemberAccess End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newNode = DirectCast(MyBase.VisitIdentifierName(node), SimpleNameSyntax) Return VisitSimpleName(newNode, node) End Function Private Function VisitSimpleName(rewrittenSimpleName As SimpleNameSyntax, originalSimpleName As SimpleNameSyntax) As ExpressionSyntax _cancellationToken.ThrowIfCancellationRequested() Dim identifier = rewrittenSimpleName.Identifier Dim newNode As ExpressionSyntax = rewrittenSimpleName ' ' 1. if this identifier is an alias, we'll expand it here and replace the node completely. ' If originalSimpleName.Kind = SyntaxKind.IdentifierName Then Dim aliasInfo = _semanticModel.GetAliasInfo(DirectCast(originalSimpleName, IdentifierNameSyntax)) If aliasInfo IsNot Nothing Then Dim aliasTarget = aliasInfo.Target If aliasTarget.IsNamespace() AndAlso DirectCast(aliasTarget, INamespaceSymbol).IsGlobalNamespace Then Return rewrittenSimpleName End If ' if the enclosing expression is a typeof expression that already contains open type we cannot ' we need to insert an open type as well. Dim typeOfExpression = originalSimpleName.GetAncestor(Of TypeOfExpressionSyntax)() If typeOfExpression IsNot Nothing AndAlso IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression) Then aliasTarget = DirectCast(aliasTarget, INamedTypeSymbol).ConstructUnboundGenericType() End If ' the expanded form replaces the current identifier name. Dim replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode:=True) _ .WithAdditionalAnnotations(Simplifier.Annotation) If replacement.Kind = SyntaxKind.QualifiedName Then Dim qualifiedReplacement = DirectCast(replacement, QualifiedNameSyntax) Dim newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Right.Identifier) If Me._annotationForReplacedAliasIdentifier IsNot Nothing Then newIdentifier = newIdentifier.WithAdditionalAnnotations(Me._annotationForReplacedAliasIdentifier) End If Dim aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name) newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo) replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier(newIdentifier)) replacement = newNode.CopyAnnotationsTo(replacement) Return replacement End If If replacement.IsKind(SyntaxKind.IdentifierName) Then Dim identifierReplacement = DirectCast(replacement, IdentifierNameSyntax) Dim newIdentifier = identifier.CopyAnnotationsTo(identifierReplacement.Identifier) If Me._annotationForReplacedAliasIdentifier IsNot Nothing Then newIdentifier = newIdentifier.WithAdditionalAnnotations(Me._annotationForReplacedAliasIdentifier) End If Dim aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name) newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo) replacement = replacement.ReplaceToken(identifier, newIdentifier) replacement = newNode.CopyAnnotationsTo(replacement) Return replacement End If Throw New NotImplementedException() End If End If Dim symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol If symbol Is Nothing Then Return newNode End If ' ' 2. If it's an attribute, make sure the identifier matches the attribute's class name without the attribute suffix. ' If originalSimpleName.GetAncestor(Of AttributeSyntax)() IsNot Nothing Then If symbol.IsConstructor() AndAlso symbol.ContainingType?.IsAttribute() Then symbol = symbol.ContainingType Dim name = symbol.Name Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText, StringComparison.Ordinal)) ' Note, VB can't escape attribute names like C#, so we actually need to expand to the symbol name ' without a suffix, see http://msdn.microsoft.com/en-us/library/aa711866(v=vs.71).aspx Dim newName = String.Empty If name.TryGetWithoutAttributeSuffix(isCaseSensitive:=False, result:=newName) Then If identifier.ValueText <> newName Then identifier = If(identifier.IsBracketed(), identifier.CopyAnnotationsTo(SyntaxFactory.BracketedIdentifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia)), identifier.CopyAnnotationsTo(SyntaxFactory.Identifier(identifier.LeadingTrivia, newName, identifier.TrailingTrivia))) End If ' if the user already used the Attribute suffix in the attribute, we'll maintain it. If identifier.ValueText = name Then identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation) End If End If End If End If ' ' 3. Always try to escape keyword identifiers ' identifier = TryEscapeIdentifierToken(identifier) If identifier <> rewrittenSimpleName.Identifier Then Select Case newNode.Kind Case SyntaxKind.IdentifierName, SyntaxKind.GenericName newNode = DirectCast(newNode, SimpleNameSyntax).WithIdentifier(identifier).WithAdditionalAnnotations(Simplifier.Annotation) Case Else Throw New NotImplementedException() End Select End If Dim parent = originalSimpleName.Parent ' do not complexify further for location where only simple names are allowed If (TypeOf (parent) Is FieldInitializerSyntax) OrElse ((TypeOf (parent) Is DeclarationStatementSyntax) AndAlso Not TypeOf (parent) Is InheritsOrImplementsStatementSyntax) OrElse (TypeOf (parent) Is MemberAccessExpressionSyntax AndAlso parent.Kind <> SyntaxKind.SimpleMemberAccessExpression) OrElse (parent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso originalSimpleName.IsRightSideOfDot()) OrElse (parent.Kind = SyntaxKind.QualifiedName AndAlso originalSimpleName.IsRightSideOfQualifiedName()) Then Return TryAddTypeArgumentToIdentifierName(newNode, symbol) End If ' ' 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it ' ' we need to treat the constructor as type name, so just get the containing type. If symbol.IsConstructor() AndAlso parent.Kind = SyntaxKind.ObjectCreationExpression Then symbol = symbol.ContainingType End If ' if it's a namespace or type name, fully qualify it. If symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Namespace Then Return FullyQualifyIdentifierName( DirectCast(symbol, INamespaceOrTypeSymbol), newNode, originalSimpleName, replaceNode:=False) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If ' if it's a member access, we're fully qualifying the left side and make it a member access. If symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Field OrElse symbol.Kind = SymbolKind.Property Then If symbol.IsStatic OrElse (TypeOf (parent) Is CrefReferenceSyntax) OrElse _semanticModel.SyntaxTree.IsNameOfContext(originalSimpleName.SpanStart, _cancellationToken) Then newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode:=False) Else Dim left As ExpressionSyntax If Not Equals(_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken), symbol.ContainingType) Then left = SyntaxFactory.MyBaseExpression() Else left = SyntaxFactory.MeExpression() End If Dim identifiersLeadingTrivia = newNode.GetLeadingTrivia() newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol) newNode = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(newNode, SimpleNameSyntax).WithoutLeadingTrivia()) _ .WithLeadingTrivia(identifiersLeadingTrivia) End If newNode = newNode.WithAdditionalAnnotations(Simplifier.Annotation) End If Return newNode End Function Private Shared Function TryAddTypeArgumentToIdentifierName( newNode As ExpressionSyntax, symbol As ISymbol) As ExpressionSyntax If newNode.Kind = SyntaxKind.IdentifierName AndAlso symbol.Kind = SymbolKind.Method Then If DirectCast(symbol, IMethodSymbol).TypeArguments.Length <> 0 Then Dim typeArguments = DirectCast(symbol, IMethodSymbol).TypeArguments Dim genericName = SyntaxFactory.GenericName( DirectCast(newNode, IdentifierNameSyntax).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList(typeArguments.Select(Function(p) SyntaxFactory.ParseTypeName(p.ToDisplayParts(typeNameFormatWithGenerics).ToDisplayString()))))) _ .WithLeadingTrivia(newNode.GetLeadingTrivia()) _ .WithTrailingTrivia(newNode.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Simplifier.Annotation) genericName = newNode.CopyAnnotationsTo(genericName) Return genericName End If End If Return newNode End Function Private Function FullyQualifyIdentifierName( symbol As ISymbol, rewrittenNode As ExpressionSyntax, originalNode As ExpressionSyntax, replaceNode As Boolean ) As ExpressionSyntax Debug.Assert(Not replaceNode OrElse rewrittenNode.Kind = SyntaxKind.IdentifierName) ' TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. ' See GenerateExpressionSyntax(); Dim result = rewrittenNode ' only if this symbol has a containing type or namespace there is work for us to do. If replaceNode OrElse symbol.ContainingType IsNot Nothing OrElse symbol.ContainingNamespace IsNot Nothing Then Dim symbolForQualification = If(replaceNode, symbol, symbol.ContainingSymbol) rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol) Dim displayParts = symbolForQualification.ToDisplayParts(typeNameFormatWithGenerics) Dim left As ExpressionSyntax = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) ' symbol display always includes module names in the qualification, but this can sometimes break code ' (see bug 529837). ' if we don't get back the same symbol for the full qualification, then we'll omit the module name. If symbol.IsModuleMember Then Dim newSymbol = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, left, SpeculativeBindingOption.BindAsExpression).Symbol If Not symbolForQualification.Equals(newSymbol) Then displayParts = symbolForQualification.ContainingSymbol.ToDisplayParts(typeNameFormatWithGenerics) left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()) End If End If If replaceNode Then result = left _ .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) _ .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()) Debug.Assert( symbol.Equals(_semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, result, SpeculativeBindingOption.BindAsExpression).Symbol)) Return result End If ' now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier Dim parent = originalNode.Parent Dim leadingTrivia = rewrittenNode.GetLeadingTrivia() rewrittenNode = rewrittenNode.WithoutLeadingTrivia() Select Case parent.Kind Case SyntaxKind.QualifiedName result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( DirectCast(left, NameSyntax), DirectCast(rewrittenNode, SimpleNameSyntax))) Case SyntaxKind.SimpleMemberAccessExpression Dim memberAccessParent = DirectCast(parent, MemberAccessExpressionSyntax) result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, memberAccessParent.OperatorToken, DirectCast(rewrittenNode, SimpleNameSyntax))) Case Else Debug.Assert(TypeOf (rewrittenNode) Is SimpleNameSyntax) If SyntaxFacts.IsInNamespaceOrTypeContext(originalNode) OrElse TypeOf (parent) Is CrefReferenceSyntax Then Dim right = DirectCast(rewrittenNode, SimpleNameSyntax) result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName(DirectCast(left, NameSyntax), right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))) Else result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, DirectCast(left, ExpressionSyntax), SyntaxFactory.Token(SyntaxKind.DotToken), DirectCast(rewrittenNode, SimpleNameSyntax))) End If End Select result = result.WithLeadingTrivia(leadingTrivia) End If Return result End Function Private Function IsTypeOfUnboundGenericType(semanticModel As SemanticModel, typeOfExpression As TypeOfExpressionSyntax) As Boolean If typeOfExpression IsNot Nothing Then Dim type = TryCast(semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type, INamedTypeSymbol) ' It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through ' parent types too Do While type IsNot Nothing If type.IsUnboundGenericType Then Return True End If type = type.ContainingType Loop End If Return False End Function Public Overrides Function VisitLabelStatement(node As LabelStatementSyntax) As SyntaxNode _cancellationToken.ThrowIfCancellationRequested() Dim newLabelStatement = DirectCast(MyBase.VisitLabelStatement(node), LabelStatementSyntax) Dim escapedLabelToken = TryEscapeIdentifierToken(newLabelStatement.LabelToken) If newLabelStatement.LabelToken <> escapedLabelToken Then newLabelStatement = newLabelStatement.WithLabelToken(escapedLabelToken) End If Return newLabelStatement End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Test/EditAndContinue/CompileTimeSolutionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class CompileTimeSolutionProviderTests { [Theory] [CombinatorialData] public async Task TryGetCompileTimeDocumentAsync([CombinatorialValues(@"_a_X_razor.cs", @"a_X_razor.g.cs")] string generatedHintName) { var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var projectId = ProjectId.CreateNewId(); var projectFilePath = Path.Combine(TempRoot.Root, "a.csproj"); var additionalFilePath = Path.Combine(TempRoot.Root, "a", "X.razor"); var designTimeFilePath = Path.Combine(TempRoot.Root, "a", "X.razor.g.cs"); var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource(generatedHintName, "") }; var sourceGeneratedPathPrefix = Path.Combine(typeof(TestSourceGenerator).Assembly.GetName().Name, typeof(TestSourceGenerator).FullName); var analyzerConfigId = DocumentId.CreateNewId(projectId); var documentId = DocumentId.CreateNewId(projectId); var additionalDocumentId = DocumentId.CreateNewId(projectId); var designTimeDocumentId = DocumentId.CreateNewId(projectId); var designTimeSolution = workspace.CurrentSolution. AddProject(ProjectInfo.Create(projectId, VersionStamp.Default, "proj", "proj", LanguageNames.CSharp, filePath: projectFilePath)). WithProjectMetadataReferences(projectId, TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)). AddAnalyzerReference(projectId, new TestGeneratorReference(generator)). AddAdditionalDocument(additionalDocumentId, "additional", SourceText.From(""), filePath: additionalFilePath). AddAnalyzerConfigDocument(analyzerConfigId, "config", SourceText.From(""), filePath: "RazorSourceGenerator.razorencconfig"). AddDocument(documentId, "a.cs", ""). AddDocument(DocumentInfo.Create( designTimeDocumentId, name: "a", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: null, filePath: designTimeFilePath, isGenerated: true, designTimeOnly: true, documentServiceProvider: null)); var designTimeDocument = designTimeSolution.GetRequiredDocument(designTimeDocumentId); var provider = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>(); var compileTimeSolution = provider.GetCompileTimeSolution(designTimeSolution); Assert.False(compileTimeSolution.ContainsAnalyzerConfigDocument(analyzerConfigId)); Assert.False(compileTimeSolution.ContainsDocument(designTimeDocumentId)); Assert.True(compileTimeSolution.ContainsDocument(documentId)); var sourceGeneratedDoc = (await compileTimeSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var compileTimeDocument = await CompileTimeSolutionProvider.TryGetCompileTimeDocumentAsync(designTimeDocument, compileTimeSolution, CancellationToken.None, sourceGeneratedPathPrefix); Assert.Same(sourceGeneratedDoc, compileTimeDocument); var actualDesignTimeDocumentIds = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, ImmutableArray.Create(documentId, sourceGeneratedDoc.Id), designTimeSolution, CancellationToken.None, sourceGeneratedPathPrefix); AssertEx.Equal(new[] { documentId, designTimeDocumentId }, actualDesignTimeDocumentIds); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class CompileTimeSolutionProviderTests { [Theory] [CombinatorialData] public async Task TryGetCompileTimeDocumentAsync([CombinatorialValues(@"_a_X_razor.cs", @"a_X_razor.g.cs")] string generatedHintName) { var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var projectId = ProjectId.CreateNewId(); var projectFilePath = Path.Combine(TempRoot.Root, "a.csproj"); var additionalFilePath = Path.Combine(TempRoot.Root, "a", "X.razor"); var designTimeFilePath = Path.Combine(TempRoot.Root, "a", "X.razor.g.cs"); var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource(generatedHintName, "") }; var sourceGeneratedPathPrefix = Path.Combine(typeof(TestSourceGenerator).Assembly.GetName().Name, typeof(TestSourceGenerator).FullName); var analyzerConfigId = DocumentId.CreateNewId(projectId); var documentId = DocumentId.CreateNewId(projectId); var additionalDocumentId = DocumentId.CreateNewId(projectId); var designTimeDocumentId = DocumentId.CreateNewId(projectId); var designTimeSolution = workspace.CurrentSolution. AddProject(ProjectInfo.Create(projectId, VersionStamp.Default, "proj", "proj", LanguageNames.CSharp, filePath: projectFilePath)). WithProjectMetadataReferences(projectId, TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)). AddAnalyzerReference(projectId, new TestGeneratorReference(generator)). AddAdditionalDocument(additionalDocumentId, "additional", SourceText.From(""), filePath: additionalFilePath). AddAnalyzerConfigDocument(analyzerConfigId, "config", SourceText.From(""), filePath: "RazorSourceGenerator.razorencconfig"). AddDocument(documentId, "a.cs", ""). AddDocument(DocumentInfo.Create( designTimeDocumentId, name: "a", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: null, filePath: designTimeFilePath, isGenerated: true, designTimeOnly: true, documentServiceProvider: null)); var designTimeDocument = designTimeSolution.GetRequiredDocument(designTimeDocumentId); var provider = workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>(); var compileTimeSolution = provider.GetCompileTimeSolution(designTimeSolution); Assert.False(compileTimeSolution.ContainsAnalyzerConfigDocument(analyzerConfigId)); Assert.False(compileTimeSolution.ContainsDocument(designTimeDocumentId)); Assert.True(compileTimeSolution.ContainsDocument(documentId)); var sourceGeneratedDoc = (await compileTimeSolution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var compileTimeDocument = await CompileTimeSolutionProvider.TryGetCompileTimeDocumentAsync(designTimeDocument, compileTimeSolution, CancellationToken.None, sourceGeneratedPathPrefix); Assert.Same(sourceGeneratedDoc, compileTimeDocument); var actualDesignTimeDocumentIds = await CompileTimeSolutionProvider.GetDesignTimeDocumentsAsync( compileTimeSolution, ImmutableArray.Create(documentId, sourceGeneratedDoc.Id), designTimeSolution, CancellationToken.None, sourceGeneratedPathPrefix); AssertEx.Equal(new[] { documentId, designTimeDocumentId }, actualDesignTimeDocumentIds); } } }
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_Projections.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.VisualStudio.Text.Projection Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class VisualBasicCompletionCommandHandlerTests_Projections <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleWithJustSubjectBuffer() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ Option Strict Off Option Explicit On Imports System Namespace ASP Public Class _Page_Views_Home_Index_vbhtml Private Shared __o As Object Public Sub Execute() #ExternalSource ("Index.vbhtml", 1) __o = AppDomain$$ #End ExternalSource End Sub End Class End Namespace ]]></Document>) state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("Curr") Await state.AssertSelectedCompletionItem(displayText:="CurrentDomain") state.SendTab() Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDot() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ {|S2: Class C Sub Goo() System$$ End Sub End Class |}]]></Document>) Dim subjectDocument = state.Workspace.Documents.First() Dim firstProjection = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1: &lt;html&gt;@|} {|S2:|} </Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1:|} {|S2:&lt;/html&gt;|} </Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim view = topProjectionBuffer.GetTextView() Dim buffer = subjectDocument.GetTextBuffer() state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer) Await state.AssertCompletionSession(view) state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer) Await state.AssertSelectedCompletionItem(displayText:="Console", projectionsView:=view) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInObjectCreationExpression() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ {|S2: Class C Sub Goo() Dim s As New$$ End Sub End Class |}]]></Document>) Dim subjectDocument = state.Workspace.Documents.First() Dim firstProjection = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1: &lt;html&gt;@|} {|S2:|} </Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1:|} {|S2:&lt;/html&gt;|} </Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim view = topProjectionBuffer.GetTextView() Dim buffer = subjectDocument.GetTextBuffer() state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer) Await state.AssertCompletionSession(view) state.SendTypeCharsToSpecificViewAndBuffer("Str", view, buffer) Await state.AssertSelectedCompletionItem(displayText:="String", isHardSelected:=True, projectionsView:=view) 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 Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.VisualStudio.Text.Projection Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class VisualBasicCompletionCommandHandlerTests_Projections <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleWithJustSubjectBuffer() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ Option Strict Off Option Explicit On Imports System Namespace ASP Public Class _Page_Views_Home_Index_vbhtml Private Shared __o As Object Public Sub Execute() #ExternalSource ("Index.vbhtml", 1) __o = AppDomain$$ #End ExternalSource End Sub End Class End Namespace ]]></Document>) state.SendTypeChars(".") Await state.AssertCompletionSession() state.SendTypeChars("Curr") Await state.AssertSelectedCompletionItem(displayText:="CurrentDomain") state.SendTab() Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDot() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ {|S2: Class C Sub Goo() System$$ End Sub End Class |}]]></Document>) Dim subjectDocument = state.Workspace.Documents.First() Dim firstProjection = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1: &lt;html&gt;@|} {|S2:|} </Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1:|} {|S2:&lt;/html&gt;|} </Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim view = topProjectionBuffer.GetTextView() Dim buffer = subjectDocument.GetTextBuffer() state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer) Await state.AssertCompletionSession(view) state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer) Await state.AssertSelectedCompletionItem(displayText:="Console", projectionsView:=view) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInObjectCreationExpression() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ {|S2: Class C Sub Goo() Dim s As New$$ End Sub End Class |}]]></Document>) Dim subjectDocument = state.Workspace.Documents.First() Dim firstProjection = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1: &lt;html&gt;@|} {|S2:|} </Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument( <Document> {|S1:|} {|S2:&lt;/html&gt;|} </Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans) Dim view = topProjectionBuffer.GetTextView() Dim buffer = subjectDocument.GetTextBuffer() state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer) Await state.AssertCompletionSession(view) state.SendTypeCharsToSpecificViewAndBuffer("Str", view, buffer) Await state.AssertSelectedCompletionItem(displayText:="String", isHardSelected:=True, projectionsView:=view) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Supprimer cette valeur quand une autre est ajoutée.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Supprimer cette valeur quand une autre est ajoutée.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,716
Lazily evaluate the root node for syntax trees
This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
chsienki
2021-08-19T00:12:46Z
2021-08-27T00:23:46Z
7b1cd60de189e60d5f91497f9b4d226f98f6b29a
6c9697c56fe39d2335b61ae7c6b342e7b76779ef
Lazily evaluate the root node for syntax trees. This avoids an issue where we continually recover syntax trees in the IDE, even when they havn't changed, which has a noticeable perf impact.
./src/Workspaces/CSharpTest/Formatting/CSharpFormattingTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Formatting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class CSharpFormattingTestBase : FormattingTestBase { private Workspace _ws; protected Workspace DefaultWorkspace => _ws ?? (_ws = new AdhocWorkspace()); protected override SyntaxNode ParseCompilation(string text, ParseOptions parseOptions) => SyntaxFactory.ParseCompilationUnit(text, options: (CSharpParseOptions)parseOptions); private protected Task AssertNoFormattingChangesAsync( string code, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(code, code, SpecializedCollections.SingletonEnumerable(new TextSpan(0, code.Length)), debugMode, changedOptionSet, testWithTransformation, parseOptions); } private protected Task AssertFormatAsync( string expected, string code, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(expected, code, SpecializedCollections.SingletonEnumerable(new TextSpan(0, code.Length)), debugMode, changedOptionSet, testWithTransformation, parseOptions); } private protected Task AssertFormatAsync( string expected, string code, IEnumerable<TextSpan> spans, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(expected, code, spans, LanguageNames.CSharp, debugMode, changedOptionSet, testWithTransformation, parseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Formatting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { public class CSharpFormattingTestBase : FormattingTestBase { private Workspace _ws; protected Workspace DefaultWorkspace => _ws ?? (_ws = new AdhocWorkspace()); protected override SyntaxNode ParseCompilation(string text, ParseOptions parseOptions) => SyntaxFactory.ParseCompilationUnit(text, options: (CSharpParseOptions)parseOptions); private protected Task AssertNoFormattingChangesAsync( string code, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(code, code, SpecializedCollections.SingletonEnumerable(new TextSpan(0, code.Length)), debugMode, changedOptionSet, testWithTransformation, parseOptions); } private protected Task AssertFormatAsync( string expected, string code, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(expected, code, SpecializedCollections.SingletonEnumerable(new TextSpan(0, code.Length)), debugMode, changedOptionSet, testWithTransformation, parseOptions); } private protected Task AssertFormatAsync( string expected, string code, IEnumerable<TextSpan> spans, bool debugMode = false, OptionsCollection changedOptionSet = null, bool testWithTransformation = true, ParseOptions parseOptions = null) { return AssertFormatAsync(expected, code, spans, LanguageNames.CSharp, debugMode, changedOptionSet, testWithTransformation, parseOptions); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/SyntaxAwareGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities.TestGenerators; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class SyntaxAwareGeneratorTests : CSharpTestBase { [Fact] public void Syntax_Receiver_Is_Present_When_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); } [Fact] public void Syntax_Receiver_Is_Null_WhenNot_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Null(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Present_When_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxContextReceiver>(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Null_WhenNot_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Null(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Null_When_Syntax_Receiver_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxReceiver = null; ISyntaxContextReceiver? contextReceiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => { syntaxReceiver = e.SyntaxReceiver; contextReceiver = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Null(contextReceiver); Assert.NotNull(syntaxReceiver); } [Fact] public void Syntax_Receiver_Is_Null_When_SyntaxContext_Receiver_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxReceiver = null; ISyntaxContextReceiver? contextReceiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => { syntaxReceiver = e.SyntaxReceiver; contextReceiver = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Null(syntaxReceiver); Assert.NotNull(contextReceiver); } [Fact] public void Syntax_Receiver_Can_Be_Registered_Only_Once() { // ISyntaxReceiver + ISyntaxReceiver GeneratorInitializationContext init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); }); // ISyntaxContextReceiver + ISyntaxContextReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); }); // ISyntaxContextReceiver + ISyntaxReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); }); // ISyntaxReceiver + ISyntaxContextReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); }); } [Fact] public void Syntax_Receiver_Visits_Syntax_In_Compilation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); } [Fact] public void SyntaxContext_Receiver_Visits_Syntax_In_Compilation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxContextReceiver>(receiver); TestSyntaxContextReceiver testReceiver = (TestSyntaxContextReceiver)receiver!; Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0].Node); Assert.NotNull(testReceiver.VisitedNodes[0].SemanticModel); Assert.Equal(testReceiver.VisitedNodes[0].SemanticModel.SyntaxTree, testReceiver.VisitedNodes[0].Node.SyntaxTree); } [Fact] public void Syntax_Receiver_Is_Not_Reused_Between_Invocations() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; int invocations = 0; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(++invocations)), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(1, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); var previousReceiver = receiver; driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.NotEqual(receiver, previousReceiver); testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(2, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); } [Fact] public void Syntax_Receiver_Exception_During_Creation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxReceiverCreator)(() => throw exception)), onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Exception_During_Visit() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is AssignmentExpressionSyntax) throw exception; })), onExecute: (e) => { e.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Exception_During_Visit_Stops_Visits_On_Other_Trees() { var source1 = @" class C { int Property { get; set; } } "; var source2 = @" class D { public void Method() { } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Equal(2, compilation.SyntaxTrees.Count()); TestSyntaxReceiver receiver1 = new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is PropertyDeclarationSyntax) throw new Exception("Test Exception"); }); var testGenerator1 = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => receiver1), onExecute: (e) => { } ); TestSyntaxReceiver receiver2 = new TestSyntaxReceiver(tag: 1); var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForSyntaxNotifications(() => receiver2), onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator1, testGenerator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.DoesNotContain(receiver1.VisitedNodes, n => n is MethodDeclarationSyntax); Assert.Contains(receiver2.VisitedNodes, n => n is MethodDeclarationSyntax); } [Fact] public void Syntax_Receiver_Exception_During_Visit_Doesnt_Stop_Other_Receivers() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is AssignmentExpressionSyntax) throw exception; })), onExecute: (e) => { } ); ISyntaxReceiver? receiver = null; var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 1)), onExecute: (e) => { receiver = e.SyntaxReceiver; e.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Equal(2, results.Results.Length); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); Assert.Empty(results.Results[1].Diagnostics); var testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(1, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Is_Not_Created_If_Exception_During_Initialize() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); TestSyntaxReceiver? receiver = null; var exception = new Exception("test exception"); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => receiver = new TestSyntaxReceiver()); throw exception; }, onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Null(receiver); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "Exception", "test exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Return_Null_During_Creation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxRx = null; ISyntaxContextReceiver? syntaxContextRx = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxReceiverCreator)(() => null!)), onExecute: (e) => { syntaxRx = e.SyntaxReceiver; syntaxContextRx = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); outputDiagnostics.Verify(); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Null(syntaxContextRx); Assert.Null(syntaxRx); } [Fact] public void Syntax_Receiver_Is_Not_Created_If_Exception_During_PostInitialize() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); TestSyntaxReceiver? receiver = null; var exception = new Exception("test exception"); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => receiver = new TestSyntaxReceiver()); i.RegisterForPostInitialization((pic) => throw exception); }, onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Null(receiver); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "Exception", "test exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Visits_Syntax_Added_In_PostInit() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var source2 = @" class D { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", source2)); }, onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; var classDeclarations = testReceiver.VisitedNodes.OfType<ClassDeclarationSyntax>().Select(c => c.Identifier.Text); Assert.Equal(new[] { "C", "D" }, classDeclarations); } [Fact] public void Syntax_Receiver_Visits_Syntax_Added_In_PostInit_From_Other_Generator() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var source2 = @" class D { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", source2)), onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; var classDeclarations = testReceiver.VisitedNodes.OfType<ClassDeclarationSyntax>().Select(c => c.Identifier.Text); Assert.Equal(new[] { "C", "D" }, classDeclarations); } [Fact] public void Syntax_Receiver_Can_Access_Types_Added_In_PostInit() { var source = @" class C : D { } "; var postInitSource = @" class D { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); Assert.Single(compilation.SyntaxTrees); compilation.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // class C : D Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(2, 11) ); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver(callback: (ctx) => { if (ctx.Node is ClassDeclarationSyntax cds && cds.Identifier.Value?.ToString() == "C") { // ensure we can query the semantic model for D var dType = ctx.SemanticModel.Compilation.GetTypeByMetadataName("D"); Assert.NotNull(dType); Assert.False(dType.IsErrorType()); // and the code referencing it now works var typeInfo = ctx.SemanticModel.GetTypeInfo(cds.BaseList!.Types[0].Type); Assert.Same(dType, typeInfo.Type); } })); i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", postInitSource)); }, onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); } [Fact] public void SyntaxContext_Receiver_Return_Null_During_Creation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxRx = null; ISyntaxContextReceiver? syntaxContextRx = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxContextReceiverCreator)(() => null!)), onExecute: (e) => { syntaxRx = e.SyntaxReceiver; syntaxContextRx = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); outputDiagnostics.Verify(); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Null(syntaxContextRx); Assert.Null(syntaxRx); } [Fact] public void IncrementalGenerator_With_Syntax_Filter() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); } [Fact] public void IncrementalGenerator_With_Multiple_Filters() { var source1 = @" #pragma warning disable CS0414 class classC { string fieldA = null; } "; var source2 = @" #pragma warning disable CS0414 class classD { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); }); var source2 = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is ClassDeclarationSyntax fds, (c, _) => ((ClassDeclarationSyntax)c.Node).Identifier.ValueText); context.RegisterSourceOutput(source2, (spc, className) => { spc.AddSource(className, ""); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("classC.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("classD.cs", results.GeneratedTrees[2].FilePath); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Does_Not_Run_When_Not_Changed() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // clear out the collected state and run again on the *same* compilation fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); // we produced the same source, but didn't call back at all Assert.Empty(fieldsCalledFor); // now change the compilation, but don't change the syntax trees compilation = compilation.WithAssemblyName("newCompilation"); fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Added_Tree() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldD = null; string fieldE = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal(3, fieldsCalledFor.Count); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // add the second tree and re-run fieldsCalledFor.Clear(); compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source2, parseOptions)); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(5, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.EndsWith("fieldD.cs", results.GeneratedTrees[3].FilePath); Assert.EndsWith("fieldE.cs", results.GeneratedTrees[4].FilePath); Assert.Equal(2, fieldsCalledFor.Count); Assert.Equal("fieldD", fieldsCalledFor[0]); Assert.Equal("fieldE", fieldsCalledFor[1]); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Removed_Tree() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldD = null; string fieldE = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(5, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.EndsWith("fieldD.cs", results.GeneratedTrees[3].FilePath); Assert.EndsWith("fieldE.cs", results.GeneratedTrees[4].FilePath); Assert.Equal(5, fieldsCalledFor.Count); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); Assert.Equal("fieldD", fieldsCalledFor[3]); Assert.Equal("fieldE", fieldsCalledFor[4]); // remove the second tree and re-run fieldsCalledFor.Clear(); compilation = compilation.RemoveSyntaxTrees(compilation.SyntaxTrees.Last()); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Runs_Only_For_Changed_Trees() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldB = null; }"; var source3 = @" #pragma warning disable CS0414 class E { string fieldC = null; }"; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2, source3 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // edit one of the syntax trees var firstTree = compilation.SyntaxTrees.First(); var newTree = CSharpSyntaxTree.ParseText(@" #pragma warning disable CS0414 class F { string fieldD = null; }", parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, newTree); // now re-run the drivers fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); // we produced the expected modified sources, but only called for the one different tree Assert.EndsWith("fieldD.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Single(fieldsCalledFor, "fieldD"); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Changed_Tree_Order() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldB = null; }"; var source3 = @" #pragma warning disable CS0414 class E { string fieldC = null; }"; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2, source3 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); List<string> syntaxFieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => { if (c is FieldDeclarationSyntax fds) { syntaxFieldsCalledFor.Add(fds.Declaration.Variables[0].Identifier.ValueText); return true; } return false; }, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); Assert.Equal("fieldA", syntaxFieldsCalledFor[0]); Assert.Equal("fieldB", syntaxFieldsCalledFor[1]); Assert.Equal("fieldC", syntaxFieldsCalledFor[2]); //swap the order of the first and last trees var firstTree = compilation.SyntaxTrees.First(); var lastTree = compilation.SyntaxTrees.Last(); var dummyTree = CSharpSyntaxTree.ParseText("", parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, dummyTree) .ReplaceSyntaxTree(lastTree, firstTree) .ReplaceSyntaxTree(dummyTree, lastTree); // now re-run the drivers and confirm we didn't actually run fieldsCalledFor.Clear(); syntaxFieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); Assert.Empty(syntaxFieldsCalledFor); // swap a tree for a tree with the same contents, but a new reference var newLastTree = CSharpSyntaxTree.ParseText(lastTree.ToString(), parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, dummyTree) .ReplaceSyntaxTree(lastTree, firstTree) .ReplaceSyntaxTree(dummyTree, newLastTree); // now re-run the drivers and confirm we only ran for the 'new' syntax tree // but then stopped when we got the same value out fieldsCalledFor.Clear(); syntaxFieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); Assert.Single(syntaxFieldsCalledFor); Assert.Equal("fieldC", syntaxFieldsCalledFor[0]); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Can_Have_Comparer() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> calledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); context.RegisterSourceOutput(source, (spc, fieldName) => { calledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, calledFor); // when we run it again, we get the same fields called for // even though they were cached, because of our comparer calledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, calledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Doesnt_Do_Duplicate_Work() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); context.RegisterSourceOutput(source, (spc, fieldName) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we only call the syntax transform once, even though we created multiple nodes via the withComparer Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Can_Feed_Two_Outputs() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> noCompareCalledFor = new List<string>(); List<string> compareCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); context.RegisterSourceOutput(source, (spc, fieldName) => { noCompareCalledFor.Add(fieldName); }); var comparerSource = source.WithComparer(new LambdaComparer<string>((a, b) => false)); context.RegisterSourceOutput(comparerSource, (spc, fieldName) => { compareCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform twice, one for each output, even though we duplicated them Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, noCompareCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, compareCalledFor); // now, when we re-run, both transforms will run, but only the comparer output will re-run syntaxCalledFor.Clear(); noCompareCalledFor.Clear(); compareCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); Assert.Empty(noCompareCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, compareCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Can_Feed_Two_Outputs() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> output1CalledFor = new List<string>(); List<string> output2CalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); context.RegisterSourceOutput(source, (spc, fieldName) => { output1CalledFor.Add("Output1_" + fieldName); }); context.RegisterSourceOutput(source, (spc, fieldName) => { output2CalledFor.Add("Output2_" + fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform once, but fed both outputs Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", }, syntaxCalledFor); Assert.Equal(new[] { "Output1_fieldA", "Output1_fieldB", "Output1_fieldC" }, output1CalledFor); Assert.Equal(new[] { "Output2_fieldA", "Output2_fieldB", "Output2_fieldC" }, output2CalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Isnt_Duplicated_By_Combines() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> outputCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); var source2 = source.Combine(context.AdditionalTextsProvider.Collect()) .Combine(context.AnalyzerConfigOptionsProvider) .Combine(context.ParseOptionsProvider); context.RegisterSourceOutput(source2, (spc, output) => { outputCalledFor.Add(output.Left.Left.Left); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we only ran the syntax transform once, even though we called through a join Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, outputCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Survive_Combines() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> outputCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); var comparerSource = source.WithComparer(new LambdaComparer<string>((a, b) => false)); // now join the two sources together var joinedSource = source.Combine(comparerSource.Collect()); context.RegisterSourceOutput(joinedSource, (spc, fieldName) => { outputCalledFor.Add(fieldName.Left); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform twice, one for each input node, but only called into the output once Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, outputCalledFor); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Filter() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider((s, _) => { if (s is AssignmentExpressionSyntax) throw exception; return true; }, (c, _) => c.Node), (spc, s) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Transform() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider<object>((s, _) => s is AssignmentExpressionSyntax, (c, _) => throw exception), (spc, s) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Transform_Doesnt_Stop_Other_Generators() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider<object>((s, _) => s is AssignmentExpressionSyntax, (c, _) => throw exception), (spc, s) => { }); }); var testGenerator2 = new PipelineCallbackGenerator2(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, s) => spc.AddSource("test", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator), new IncrementalGeneratorWrapper(testGenerator2) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); Assert.Single(results.Results[1].GeneratedSources); Assert.Null(results.Results[1].Exception); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Incremental_Generators_Can_Be_Cancelled_During_Syntax() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); int filterCalled = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { filterCalled++; if (c is AssignmentExpressionSyntax) cts.Cancel(); return true; }, (a, _) => a); ctx.RegisterSourceOutput(step1, (spc, c) => spc.AddSource("step1", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.Equal(19, filterCalled); } [Fact] public void Incremental_Generators_Can_Be_Cancelled_During_Syntax_And_Stop_Other_SyntaxVisits() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { generatorCancelled = true; cts.Cancel(); return true; }, (a, _) => a); ctx.RegisterSourceOutput(step1, (spc, c) => spc.AddSource("step1", "")); var step2 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { return true; }, (a, _) => a); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("step2", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } private class TestReceiverBase<T> { private readonly Action<T>? _callback; public List<T> VisitedNodes { get; } = new List<T>(); public int Tag { get; } public TestReceiverBase(int tag = 0, Action<T>? callback = null) { Tag = tag; _callback = callback; } public void OnVisitSyntaxNode(T syntaxNode) { VisitedNodes.Add(syntaxNode); if (_callback is object) { _callback(syntaxNode); } } } private class TestSyntaxReceiver : TestReceiverBase<SyntaxNode>, ISyntaxReceiver { public TestSyntaxReceiver(int tag = 0, Action<SyntaxNode>? callback = null) : base(tag, callback) { } } private class TestSyntaxContextReceiver : TestReceiverBase<GeneratorSyntaxContext>, ISyntaxContextReceiver { public TestSyntaxContextReceiver(int tag = 0, Action<GeneratorSyntaxContext>? callback = null) : base(tag, callback) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities.TestGenerators; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class SyntaxAwareGeneratorTests : CSharpTestBase { [Fact] public void Syntax_Receiver_Is_Present_When_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); } [Fact] public void Syntax_Receiver_Is_Null_WhenNot_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Null(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Present_When_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxContextReceiver>(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Null_WhenNot_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Null(receiver); } [Fact] public void SyntaxContext_Receiver_Is_Null_When_Syntax_Receiver_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxReceiver = null; ISyntaxContextReceiver? contextReceiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => { syntaxReceiver = e.SyntaxReceiver; contextReceiver = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Null(contextReceiver); Assert.NotNull(syntaxReceiver); } [Fact] public void Syntax_Receiver_Is_Null_When_SyntaxContext_Receiver_Registered() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxReceiver = null; ISyntaxContextReceiver? contextReceiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => { syntaxReceiver = e.SyntaxReceiver; contextReceiver = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Null(syntaxReceiver); Assert.NotNull(contextReceiver); } [Fact] public void Syntax_Receiver_Can_Be_Registered_Only_Once() { // ISyntaxReceiver + ISyntaxReceiver GeneratorInitializationContext init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); }); // ISyntaxContextReceiver + ISyntaxContextReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); }); // ISyntaxContextReceiver + ISyntaxReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); }); // ISyntaxReceiver + ISyntaxContextReceiver init = new GeneratorInitializationContext(CancellationToken.None); init.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); Assert.Throws<InvalidOperationException>(() => { init.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()); }); } [Fact] public void Syntax_Receiver_Visits_Syntax_In_Compilation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); } [Fact] public void SyntaxContext_Receiver_Visits_Syntax_In_Compilation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxContextReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver()), onExecute: (e) => receiver = e.SyntaxContextReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxContextReceiver>(receiver); TestSyntaxContextReceiver testReceiver = (TestSyntaxContextReceiver)receiver!; Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0].Node); Assert.NotNull(testReceiver.VisitedNodes[0].SemanticModel); Assert.Equal(testReceiver.VisitedNodes[0].SemanticModel.SyntaxTree, testReceiver.VisitedNodes[0].Node.SyntaxTree); } [Fact] public void Syntax_Receiver_Is_Not_Reused_Between_Non_Cached_Invocations() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; int invocations = 0; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(++invocations)), onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(1, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); // update the compilation. In v1 we always re-created the receiver, but in v2 we only re-create // it if the compilation has changed. compilation = compilation.WithAssemblyName("modified"); var previousReceiver = receiver; driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.NotEqual(receiver, previousReceiver); testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(2, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); Assert.IsType<CompilationUnitSyntax>(testReceiver.VisitedNodes[0]); } [Fact] public void Syntax_Receiver_Exception_During_Creation() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxReceiverCreator)(() => throw exception)), onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Exception_During_Visit() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is AssignmentExpressionSyntax) throw exception; })), onExecute: (e) => { e.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Exception_During_Visit_Stops_Visits_On_Other_Trees() { var source1 = @" class C { int Property { get; set; } } "; var source2 = @" class D { public void Method() { } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Equal(2, compilation.SyntaxTrees.Count()); TestSyntaxReceiver receiver1 = new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is PropertyDeclarationSyntax) throw new Exception("Test Exception"); }); var testGenerator1 = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => receiver1), onExecute: (e) => { } ); TestSyntaxReceiver receiver2 = new TestSyntaxReceiver(tag: 1); var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForSyntaxNotifications(() => receiver2), onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator1, testGenerator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.DoesNotContain(receiver1.VisitedNodes, n => n is MethodDeclarationSyntax); Assert.Contains(receiver2.VisitedNodes, n => n is MethodDeclarationSyntax); } [Fact] public void Syntax_Receiver_Exception_During_Visit_Doesnt_Stop_Other_Receivers() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 0, callback: (a) => { if (a is AssignmentExpressionSyntax) throw exception; })), onExecute: (e) => { } ); ISyntaxReceiver? receiver = null; var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver(tag: 1)), onExecute: (e) => { receiver = e.SyntaxReceiver; e.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Equal(2, results.Results.Length); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); Assert.Empty(results.Results[1].Diagnostics); var testReceiver = (TestSyntaxReceiver)receiver!; Assert.Equal(1, testReceiver.Tag); Assert.Equal(21, testReceiver.VisitedNodes.Count); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Is_Not_Created_If_Exception_During_Initialize() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); TestSyntaxReceiver? receiver = null; var exception = new Exception("test exception"); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => receiver = new TestSyntaxReceiver()); throw exception; }, onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Null(receiver); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "Exception", "test exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Return_Null_During_Creation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxRx = null; ISyntaxContextReceiver? syntaxContextRx = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxReceiverCreator)(() => null!)), onExecute: (e) => { syntaxRx = e.SyntaxReceiver; syntaxContextRx = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); outputDiagnostics.Verify(); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Null(syntaxContextRx); Assert.Null(syntaxRx); } [Fact] public void Syntax_Receiver_Is_Not_Created_If_Exception_During_PostInitialize() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); TestSyntaxReceiver? receiver = null; var exception = new Exception("test exception"); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => receiver = new TestSyntaxReceiver()); i.RegisterForPostInitialization((pic) => throw exception); }, onExecute: (e) => { Assert.True(false); } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Null(receiver); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "Exception", "test exception").WithLocation(1, 1) ); } [Fact] public void Syntax_Receiver_Visits_Syntax_Added_In_PostInit() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var source2 = @" class D { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()); i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", source2)); }, onExecute: (e) => receiver = e.SyntaxReceiver ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; var classDeclarations = testReceiver.VisitedNodes.OfType<ClassDeclarationSyntax>().Select(c => c.Identifier.Text); Assert.Equal(new[] { "C", "D" }, classDeclarations); } [Fact] public void Syntax_Receiver_Visits_Syntax_Added_In_PostInit_From_Other_Generator() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var source2 = @" class D { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? receiver = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications(() => new TestSyntaxReceiver()), onExecute: (e) => receiver = e.SyntaxReceiver ); var testGenerator2 = new CallbackGenerator2( onInit: (i) => i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", source2)), onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(receiver); Assert.IsType<TestSyntaxReceiver>(receiver); TestSyntaxReceiver testReceiver = (TestSyntaxReceiver)receiver!; var classDeclarations = testReceiver.VisitedNodes.OfType<ClassDeclarationSyntax>().Select(c => c.Identifier.Text); Assert.Equal(new[] { "C", "D" }, classDeclarations); } [Fact] public void Syntax_Receiver_Can_Access_Types_Added_In_PostInit() { var source = @" class C : D { } "; var postInitSource = @" class D { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); Assert.Single(compilation.SyntaxTrees); compilation.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // class C : D Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(2, 11) ); var testGenerator = new CallbackGenerator( onInit: (i) => { i.RegisterForSyntaxNotifications(() => new TestSyntaxContextReceiver(callback: (ctx) => { if (ctx.Node is ClassDeclarationSyntax cds && cds.Identifier.Value?.ToString() == "C") { // ensure we can query the semantic model for D var dType = ctx.SemanticModel.Compilation.GetTypeByMetadataName("D"); Assert.NotNull(dType); Assert.False(dType.IsErrorType()); // and the code referencing it now works var typeInfo = ctx.SemanticModel.GetTypeInfo(cds.BaseList!.Types[0].Type); Assert.Same(dType, typeInfo.Type); } })); i.RegisterForPostInitialization((pic) => pic.AddSource("postInit", postInitSource)); }, onExecute: (e) => { } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); } [Fact] public void SyntaxContext_Receiver_Return_Null_During_Creation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ISyntaxReceiver? syntaxRx = null; ISyntaxContextReceiver? syntaxContextRx = null; var testGenerator = new CallbackGenerator( onInit: (i) => i.RegisterForSyntaxNotifications((SyntaxContextReceiverCreator)(() => null!)), onExecute: (e) => { syntaxRx = e.SyntaxReceiver; syntaxContextRx = e.SyntaxContextReceiver; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); outputDiagnostics.Verify(); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Null(syntaxContextRx); Assert.Null(syntaxRx); } [Fact] public void IncrementalGenerator_With_Syntax_Filter() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); } [Fact] public void IncrementalGenerator_With_Multiple_Filters() { var source1 = @" #pragma warning disable CS0414 class classC { string fieldA = null; } "; var source2 = @" #pragma warning disable CS0414 class classD { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); }); var source2 = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is ClassDeclarationSyntax fds, (c, _) => ((ClassDeclarationSyntax)c.Node).Identifier.ValueText); context.RegisterSourceOutput(source2, (spc, className) => { spc.AddSource(className, ""); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("classC.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("classD.cs", results.GeneratedTrees[2].FilePath); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Does_Not_Run_When_Not_Changed() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // clear out the collected state and run again on the *same* compilation fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); // we produced the same source, but didn't call back at all Assert.Empty(fieldsCalledFor); // now change the compilation, but don't change the syntax trees compilation = compilation.WithAssemblyName("newCompilation"); fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Added_Tree() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldD = null; string fieldE = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal(3, fieldsCalledFor.Count); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // add the second tree and re-run fieldsCalledFor.Clear(); compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source2, parseOptions)); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(5, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.EndsWith("fieldD.cs", results.GeneratedTrees[3].FilePath); Assert.EndsWith("fieldE.cs", results.GeneratedTrees[4].FilePath); Assert.Equal(2, fieldsCalledFor.Count); Assert.Equal("fieldD", fieldsCalledFor[0]); Assert.Equal("fieldE", fieldsCalledFor[1]); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Removed_Tree() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldD = null; string fieldE = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(5, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.EndsWith("fieldD.cs", results.GeneratedTrees[3].FilePath); Assert.EndsWith("fieldE.cs", results.GeneratedTrees[4].FilePath); Assert.Equal(5, fieldsCalledFor.Count); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); Assert.Equal("fieldD", fieldsCalledFor[3]); Assert.Equal("fieldE", fieldsCalledFor[4]); // remove the second tree and re-run fieldsCalledFor.Clear(); compilation = compilation.RemoveSyntaxTrees(compilation.SyntaxTrees.Last()); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Runs_Only_For_Changed_Trees() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldB = null; }"; var source3 = @" #pragma warning disable CS0414 class E { string fieldC = null; }"; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2, source3 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); // edit one of the syntax trees var firstTree = compilation.SyntaxTrees.First(); var newTree = CSharpSyntaxTree.ParseText(@" #pragma warning disable CS0414 class F { string fieldD = null; }", parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, newTree); // now re-run the drivers fieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); // we produced the expected modified sources, but only called for the one different tree Assert.EndsWith("fieldD.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Single(fieldsCalledFor, "fieldD"); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Changed_Tree_Order() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; }"; var source2 = @" #pragma warning disable CS0414 class D { string fieldB = null; }"; var source3 = @" #pragma warning disable CS0414 class E { string fieldC = null; }"; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(new[] { source1, source2, source3 }, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> fieldsCalledFor = new List<string>(); List<string> syntaxFieldsCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => { if (c is FieldDeclarationSyntax fds) { syntaxFieldsCalledFor.Add(fds.Declaration.Variables[0].Identifier.ValueText); return true; } return false; }, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); context.RegisterSourceOutput(source, (spc, fieldName) => { spc.AddSource(fieldName, ""); fieldsCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Equal("fieldA", fieldsCalledFor[0]); Assert.Equal("fieldB", fieldsCalledFor[1]); Assert.Equal("fieldC", fieldsCalledFor[2]); Assert.Equal("fieldA", syntaxFieldsCalledFor[0]); Assert.Equal("fieldB", syntaxFieldsCalledFor[1]); Assert.Equal("fieldC", syntaxFieldsCalledFor[2]); //swap the order of the first and last trees var firstTree = compilation.SyntaxTrees.First(); var lastTree = compilation.SyntaxTrees.Last(); var dummyTree = CSharpSyntaxTree.ParseText("", parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, dummyTree) .ReplaceSyntaxTree(lastTree, firstTree) .ReplaceSyntaxTree(dummyTree, lastTree); // now re-run the drivers and confirm we didn't actually run fieldsCalledFor.Clear(); syntaxFieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); Assert.Empty(syntaxFieldsCalledFor); // swap a tree for a tree with the same contents, but a new reference var newLastTree = CSharpSyntaxTree.ParseText(lastTree.ToString(), parseOptions); compilation = compilation.ReplaceSyntaxTree(firstTree, dummyTree) .ReplaceSyntaxTree(lastTree, firstTree) .ReplaceSyntaxTree(dummyTree, newLastTree); // now re-run the drivers and confirm we only ran for the 'new' syntax tree // but then stopped when we got the same value out fieldsCalledFor.Clear(); syntaxFieldsCalledFor.Clear(); driver = driver.RunGenerators(compilation); results = driver.GetRunResult(); Assert.Empty(results.Diagnostics); Assert.Equal(3, results.GeneratedTrees.Length); Assert.EndsWith("fieldA.cs", results.GeneratedTrees[0].FilePath); Assert.EndsWith("fieldB.cs", results.GeneratedTrees[1].FilePath); Assert.EndsWith("fieldC.cs", results.GeneratedTrees[2].FilePath); Assert.Empty(fieldsCalledFor); Assert.Single(syntaxFieldsCalledFor); Assert.Equal("fieldC", syntaxFieldsCalledFor[0]); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Can_Have_Comparer() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var source2 = @" #pragma warning disable CS0414 class C { string fieldD = null; string fieldE = null; string fieldF = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> calledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); source = source.WithComparer(new LambdaComparer<string>((a, b) => true)); context.RegisterSourceOutput(source, (spc, fieldName) => { calledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, calledFor); // make a change to the syntax tree compilation = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText(source2, parseOptions)); // when we run it again, we get no output because the comparer has suppressed the modification calledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(calledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Doesnt_Do_Duplicate_Work() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); source = source.WithComparer(new LambdaComparer<string>((a, b) => false)); context.RegisterSourceOutput(source, (spc, fieldName) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we only call the syntax transform once, even though we created multiple nodes via the withComparer Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Can_Feed_Two_Outputs() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var source2 = @" #pragma warning disable CS0414 class C { string fieldD = null; string fieldE = null; string fieldF = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> noCompareCalledFor = new List<string>(); List<string> compareCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); context.RegisterSourceOutput(source, (spc, fieldName) => { noCompareCalledFor.Add(fieldName); }); var comparerSource = source.WithComparer(new LambdaComparer<string>((a, b) => true)); context.RegisterSourceOutput(comparerSource, (spc, fieldName) => { compareCalledFor.Add(fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform twice, one for each output, even though we duplicated them Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, noCompareCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, compareCalledFor); // make a change to the syntax tree compilation = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText(source2, parseOptions)); // now, when we re-run, both transforms will run, but the comparer will suppress the modified output syntaxCalledFor.Clear(); noCompareCalledFor.Clear(); compareCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Equal(new[] { "fieldD", "fieldE", "fieldF", "fieldD", "fieldE", "fieldF" }, syntaxCalledFor); Assert.Equal(new[] { "fieldD", "fieldE", "fieldF" }, noCompareCalledFor); Assert.Empty(compareCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Can_Feed_Two_Outputs() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> output1CalledFor = new List<string>(); List<string> output2CalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); context.RegisterSourceOutput(source, (spc, fieldName) => { output1CalledFor.Add("Output1_" + fieldName); }); context.RegisterSourceOutput(source, (spc, fieldName) => { output2CalledFor.Add("Output2_" + fieldName); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform once, but fed both outputs Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", }, syntaxCalledFor); Assert.Equal(new[] { "Output1_fieldA", "Output1_fieldB", "Output1_fieldC" }, output1CalledFor); Assert.Equal(new[] { "Output2_fieldA", "Output2_fieldB", "Output2_fieldC" }, output2CalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_Isnt_Duplicated_By_Combines() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> outputCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); var source2 = source.Combine(context.AdditionalTextsProvider.Collect()) .Combine(context.AnalyzerConfigOptionsProvider) .Combine(context.ParseOptionsProvider); context.RegisterSourceOutput(source2, (spc, output) => { outputCalledFor.Add(output.Left.Left.Left); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we only ran the syntax transform once, even though we called through a join Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, outputCalledFor); } [Fact] public void IncrementalGenerator_With_Syntax_Filter_And_Comparer_Survive_Combines() { var source1 = @" #pragma warning disable CS0414 class C { string fieldA = null; string fieldB = null; string fieldC = null; } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source1, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); List<string> syntaxCalledFor = new List<string>(); List<string> outputCalledFor = new List<string>(); var testGenerator = new PipelineCallbackGenerator(context => { var source = context.SyntaxProvider.CreateSyntaxProvider((c, _) => c is FieldDeclarationSyntax fds, (c, _) => { syntaxCalledFor.Add(((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText); return ((FieldDeclarationSyntax)c.Node).Declaration.Variables[0].Identifier.ValueText; }); var comparerSource = source.WithComparer(new LambdaComparer<string>((a, b) => false)); // now join the two sources together var joinedSource = source.Combine(comparerSource.Collect()); context.RegisterSourceOutput(joinedSource, (spc, fieldName) => { outputCalledFor.Add(fieldName.Left); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); // verify we ran the syntax transform twice, one for each input node, but only called into the output once Assert.Equal(new[] { "fieldA", "fieldB", "fieldC", "fieldA", "fieldB", "fieldC" }, syntaxCalledFor); Assert.Equal(new[] { "fieldA", "fieldB", "fieldC" }, outputCalledFor); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Filter() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider((s, _) => { if (s is AssignmentExpressionSyntax) throw exception; return true; }, (c, _) => c.Node), (spc, s) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Transform() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider<object>((s, _) => s is AssignmentExpressionSyntax, (c, _) => throw exception), (spc, s) => { }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void IncrementalGenerator_Throws_In_Syntax_Transform_Doesnt_Stop_Other_Generators() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new Exception("Test Exception"); var testGenerator = new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider<object>((s, _) => s is AssignmentExpressionSyntax, (c, _) => throw exception), (spc, s) => { }); }); var testGenerator2 = new PipelineCallbackGenerator2(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, s) => spc.AddSource("test", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { new IncrementalGeneratorWrapper(testGenerator), new IncrementalGeneratorWrapper(testGenerator2) }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Diagnostics); Assert.Single(results.Results[0].Diagnostics); Assert.NotNull(results.Results[0].Exception); Assert.Equal("Test Exception", results.Results[0].Exception?.Message); Assert.Single(results.Results[1].GeneratedSources); Assert.Null(results.Results[1].Exception); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("PipelineCallbackGenerator", "Exception", "Test Exception").WithLocation(1, 1) ); } [Fact] public void Incremental_Generators_Can_Be_Cancelled_During_Syntax() { var source = @" class C { int Property { get; set; } void Function() { var x = 5; x += 4; } } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); int filterCalled = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { filterCalled++; if (c is AssignmentExpressionSyntax) cts.Cancel(); return true; }, (a, _) => a); ctx.RegisterSourceOutput(step1, (spc, c) => spc.AddSource("step1", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.Equal(19, filterCalled); } [Fact] public void Incremental_Generators_Can_Be_Cancelled_During_Syntax_And_Stop_Other_SyntaxVisits() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { generatorCancelled = true; cts.Cancel(); return true; }, (a, _) => a); ctx.RegisterSourceOutput(step1, (spc, c) => spc.AddSource("step1", "")); var step2 = ctx.SyntaxProvider.CreateSyntaxProvider((c, ct) => { return true; }, (a, _) => a); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("step2", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } private class TestReceiverBase<T> { private readonly Action<T>? _callback; public List<T> VisitedNodes { get; } = new List<T>(); public int Tag { get; } public TestReceiverBase(int tag = 0, Action<T>? callback = null) { Tag = tag; _callback = callback; } public void OnVisitSyntaxNode(T syntaxNode) { VisitedNodes.Add(syntaxNode); if (_callback is object) { _callback(syntaxNode); } } } private class TestSyntaxReceiver : TestReceiverBase<SyntaxNode>, ISyntaxReceiver { public TestSyntaxReceiver(int tag = 0, Action<SyntaxNode>? callback = null) : base(tag, callback) { } } private class TestSyntaxContextReceiver : TestReceiverBase<GeneratorSyntaxContext>, ISyntaxContextReceiver { public TestSyntaxContextReceiver(int tag = 0, Action<GeneratorSyntaxContext>? callback = null) : base(tag, callback) { } } } }
1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/DriverStateTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { builders.Add(node.GetBuilder(_previousTable)); } // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = tree.GetRoot(_cancellationToken); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // CONSIDER: when the compilation is the same as previous, the syntax trees must also be the same. // if we have a previous state table for a node, we can just short circuit knowing that it is up to date var compilationIsCached = GetLatestStateTableForNode(SharedInputNodes.Compilation).IsCached; // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { if (compilationIsCached && _previousTable._tables.TryGetValue(node, out var previousStateTable)) { _tableBuilder.Add(node, previousStateTable); } else { builders.Add(node.GetBuilder(_previousTable)); } } if (builders.Count == 0) { // bring over the previously cached syntax tree inputs _tableBuilder[SharedInputNodes.SyntaxTrees] = _previousTable._tables[SharedInputNodes.SyntaxTrees]; } else { // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = tree.GetRoot(_cancellationToken); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // A node table is the fundamental structure we use to track changes through the incremental // generator api. It can be thought of as a series of slots that take their input from an // upstream table and produce 0-or-more outputs. When viewed from a downstream table the outputs // are presented as a single unified list, with each output forming the new input to the downstream // table. // // Each slot has an associated state which is used to inform the operation that should be performed // to create or update the outputs. States generally flow through from upstream to downstream tables. // For instance an Added state implies that the upstream table produced a value that was not seen // in the previous iteration, and the table should run whatever transform it tracks on the input // to produce the outputs. These new outputs will also have a state of Added. A cached input specifies // that the input has not changed, and thus the outputs will be the same as the previous run. Added, // and Modified inputs will always run a transform to produce new outputs. Cached and Removed // entries will always use the previous entries and perform no work. // // It is important to track Removed entries while updating the downstream tables, as an upstream // remove can result in multiple downstream entries being removed. However, once all tables are up // to date, the removed entries are no longer needed, and the remaining entries can be considered to // be cached. This process is called 'compaction' and results in the actual tables which are stored // between runs, as opposed to the 'live' tables that exist during an update. // // Modified entries are similar to added inputs, but with a subtle difference. When an input is Added // all outputs are unconditionally added too. However when an input is modified, the outputs may still // be the same (for instance something changed elsewhere in a file that had no bearing on the produced // output). In this case, the state table checks the results against the previously produced values, // and any that are found to be the same instead get a cached state, meaning no new downstream work // will be produced for them. Thus a modified input is the only slot that can have differing output // states. internal enum EntryState { Added, Removed, Modified, Cached }; internal interface IStateTable { IStateTable AsCached(); } /// <summary> /// A data structure that tracks the inputs and output of an execution node /// </summary> /// <typeparam name="T">The type of the items tracked by this table</typeparam> internal sealed class NodeStateTable<T> : IStateTable { internal static NodeStateTable<T> Empty { get; } = new NodeStateTable<T>(ImmutableArray<TableEntry>.Empty, isCompacted: true); private readonly ImmutableArray<TableEntry> _states; private NodeStateTable(ImmutableArray<TableEntry> states, bool isCompacted) { Debug.Assert(!isCompacted || states.All(s => s.IsCached)); _states = states; IsCached = isCompacted; } public int Count { get => _states.Length; } /// <summary> /// Indicates if every entry in this table has a state of <see cref="EntryState.Cached"/> /// </summary> public bool IsCached { get; } public IEnumerator<(T item, EntryState state)> GetEnumerator() { foreach (var inputEntry in _states) { for (int i = 0; i < inputEntry.Count; i++) { yield return (inputEntry.GetItem(i), inputEntry.GetState(i)); } } } public NodeStateTable<T> AsCached() { if (IsCached) return this; var compacted = ArrayBuilder<TableEntry>.GetInstance(); foreach (var entry in _states) { if (!entry.IsRemoved) { compacted.Add(entry.AsCached()); } } return new NodeStateTable<T>(compacted.ToImmutableAndFree(), isCompacted: true); } IStateTable IStateTable.AsCached() => AsCached(); public T Single() { Debug.Assert((_states.Length == 1 || _states.Length == 2 && _states[0].IsRemoved) && this._states[^1].Count == 1); return this._states[^1].GetItem(0); } public ImmutableArray<T> Batch() { var sourceBuilder = ArrayBuilder<T>.GetInstance(); foreach (var entry in this) { // we don't return removed entries to the downstream node. // we're creating a new state table as part of this call, so they're no longer needed if (entry.state != EntryState.Removed) { sourceBuilder.Add(entry.item); } } return sourceBuilder.ToImmutableAndFree(); } public Builder ToBuilder() { return new Builder(this); } public sealed class Builder { private readonly ArrayBuilder<TableEntry> _states; private readonly NodeStateTable<T> _previous; internal Builder(NodeStateTable<T> previous) { _states = ArrayBuilder<TableEntry>.GetInstance(); _previous = previous; } public void RemoveEntries() { // if a new table is asked to remove entries we can just do nothing // as it can't have any effect on downstream tables if (_previous._states.Length > _states.Count) { var previousEntries = _previous._states[_states.Count].AsRemoved(); _states.Add(previousEntries); } } public bool TryUseCachedEntries() { if (_previous._states.Length <= _states.Count) { return false; } var previousEntries = _previous._states[_states.Count]; Debug.Assert(previousEntries.IsCached); _states.Add(previousEntries); return true; } public bool TryUseCachedEntries(out ImmutableArray<T> entries) { if (!TryUseCachedEntries()) { entries = default; return false; } entries = _states[_states.Count - 1].ToImmutableArray(); return true; } public bool TryModifyEntry(T value, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } Debug.Assert(_previous._states[_states.Count].Count == 1); _states.Add(new TableEntry(value, comparer.Equals(_previous._states[_states.Count].GetItem(0), value) ? EntryState.Cached : EntryState.Modified)); return true; } public bool TryModifyEntries(ImmutableArray<T> outputs, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } // Semantics: // For each item in the row, we compare with the new matching new value. // - Cached when the same // - Modified when different // - Removed when old item position > outputs.length // - Added when new item position < previousTable.length var previousEntry = _previous._states[_states.Count]; // when both entries have no items, we can short circuit if (previousEntry.Count == 0 && outputs.Length == 0) { _states.Add(previousEntry); return true; } var modified = new TableEntry.Builder(); var sharedCount = Math.Min(previousEntry.Count, outputs.Length); // cached or modified items for (int i = 0; i < sharedCount; i++) { var previous = previousEntry.GetItem(i); var replacement = outputs[i]; var entryState = comparer.Equals(previous, replacement) ? EntryState.Cached : EntryState.Modified; modified.Add(replacement, entryState); } // removed for (int i = sharedCount; i < previousEntry.Count; i++) { modified.Add(previousEntry.GetItem(i), EntryState.Removed); } // added for (int i = sharedCount; i < outputs.Length; i++) { modified.Add(outputs[i], EntryState.Added); } _states.Add(modified.ToImmutableAndFree()); return true; } public void AddEntry(T value, EntryState state) { _states.Add(new TableEntry(value, state)); } public void AddEntries(ImmutableArray<T> values, EntryState state) { _states.Add(new TableEntry(values, state)); } public NodeStateTable<T> ToImmutableAndFree() { if (_states.Count == 0) { _states.Free(); return NodeStateTable<T>.Empty; } var hasNonCached = _states.Any(static s => !s.IsCached); return new NodeStateTable<T>(_states.ToImmutableAndFree(), isCompacted: !hasNonCached); } } private readonly struct TableEntry { private static readonly ImmutableArray<EntryState> s_allAddedEntries = ImmutableArray.Create(EntryState.Added); private static readonly ImmutableArray<EntryState> s_allCachedEntries = ImmutableArray.Create(EntryState.Cached); private static readonly ImmutableArray<EntryState> s_allModifiedEntries = ImmutableArray.Create(EntryState.Modified); private static readonly ImmutableArray<EntryState> s_allRemovedEntries = ImmutableArray.Create(EntryState.Removed); private readonly ImmutableArray<T> _items; private readonly T? _item; /// <summary> /// Represents the corresponding state of each item in <see cref="_items"/>, /// or contains a single state when <see cref="_item"/> is populated or when every state of <see cref="_items"/> has the same value. /// </summary> private readonly ImmutableArray<EntryState> _states; public TableEntry(T item, EntryState state) : this(item, default, GetSingleArray(state)) { } public TableEntry(ImmutableArray<T> items, EntryState state) : this(default, items, GetSingleArray(state)) { } private TableEntry(T? item, ImmutableArray<T> items, ImmutableArray<EntryState> states) { Debug.Assert(!states.IsDefault); Debug.Assert(states.Length == 1 || states.Distinct().Count() > 1); this._item = item; this._items = items; this._states = states; } public bool IsCached => this._states == s_allCachedEntries || this._states.All(s => s == EntryState.Cached); public bool IsRemoved => this._states == s_allRemovedEntries || this._states.All(s => s == EntryState.Removed); public int Count => IsSingle ? 1 : _items.Length; public T GetItem(int index) { Debug.Assert(!IsSingle || index == 0); return IsSingle ? _item : _items[index]; } public EntryState GetState(int index) => _states.Length == 1 ? _states[0] : _states[index]; public ImmutableArray<T> ToImmutableArray() => IsSingle ? ImmutableArray.Create(_item) : _items; public TableEntry AsCached() => new(_item, _items, s_allCachedEntries); public TableEntry AsRemoved() => new(_item, _items, s_allRemovedEntries); [MemberNotNullWhen(true, new[] { nameof(_item) })] private bool IsSingle => this._items.IsDefault; private static ImmutableArray<EntryState> GetSingleArray(EntryState state) => state switch { EntryState.Added => s_allAddedEntries, EntryState.Cached => s_allCachedEntries, EntryState.Modified => s_allModifiedEntries, EntryState.Removed => s_allRemovedEntries, _ => throw ExceptionUtilities.Unreachable }; public sealed class Builder { private readonly ArrayBuilder<T> _items = ArrayBuilder<T>.GetInstance(); private ArrayBuilder<EntryState>? _states; private EntryState? _currentState; public void Add(T item, EntryState state) { _items.Add(item); if (!_currentState.HasValue) { _currentState = state; } else if (_states is object) { _states.Add(state); } else if (_currentState != state) { _states = ArrayBuilder<EntryState>.GetInstance(_items.Count - 1, _currentState.Value); _states.Add(state); } } public TableEntry ToImmutableAndFree() { Debug.Assert(_currentState.HasValue, "Created a builder with no values?"); return new TableEntry(item: default, _items.ToImmutableAndFree(), _states?.ToImmutableAndFree() ?? GetSingleArray(_currentState.Value)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // A node table is the fundamental structure we use to track changes through the incremental // generator api. It can be thought of as a series of slots that take their input from an // upstream table and produce 0-or-more outputs. When viewed from a downstream table the outputs // are presented as a single unified list, with each output forming the new input to the downstream // table. // // Each slot has an associated state which is used to inform the operation that should be performed // to create or update the outputs. States generally flow through from upstream to downstream tables. // For instance an Added state implies that the upstream table produced a value that was not seen // in the previous iteration, and the table should run whatever transform it tracks on the input // to produce the outputs. These new outputs will also have a state of Added. A cached input specifies // that the input has not changed, and thus the outputs will be the same as the previous run. Added, // and Modified inputs will always run a transform to produce new outputs. Cached and Removed // entries will always use the previous entries and perform no work. // // It is important to track Removed entries while updating the downstream tables, as an upstream // remove can result in multiple downstream entries being removed. However, once all tables are up // to date, the removed entries are no longer needed, and the remaining entries can be considered to // be cached. This process is called 'compaction' and results in the actual tables which are stored // between runs, as opposed to the 'live' tables that exist during an update. // // Modified entries are similar to added inputs, but with a subtle difference. When an input is Added // all outputs are unconditionally added too. However when an input is modified, the outputs may still // be the same (for instance something changed elsewhere in a file that had no bearing on the produced // output). In this case, the state table checks the results against the previously produced values, // and any that are found to be the same instead get a cached state, meaning no new downstream work // will be produced for them. Thus a modified input is the only slot that can have differing output // states. internal enum EntryState { Added, Removed, Modified, Cached }; internal interface IStateTable { IStateTable AsCached(); } /// <summary> /// A data structure that tracks the inputs and output of an execution node /// </summary> /// <typeparam name="T">The type of the items tracked by this table</typeparam> internal sealed class NodeStateTable<T> : IStateTable { internal static NodeStateTable<T> Empty { get; } = new NodeStateTable<T>(ImmutableArray<TableEntry>.Empty, isCompacted: true); private readonly ImmutableArray<TableEntry> _states; private NodeStateTable(ImmutableArray<TableEntry> states, bool isCompacted) { Debug.Assert(!isCompacted || states.All(s => s.IsCached)); _states = states; IsCached = isCompacted; } public int Count { get => _states.Length; } /// <summary> /// Indicates if every entry in this table has a state of <see cref="EntryState.Cached"/> /// </summary> public bool IsCached { get; } public IEnumerator<(T item, EntryState state)> GetEnumerator() { foreach (var inputEntry in _states) { for (int i = 0; i < inputEntry.Count; i++) { yield return (inputEntry.GetItem(i), inputEntry.GetState(i)); } } } public NodeStateTable<T> AsCached() { if (IsCached) return this; var compacted = ArrayBuilder<TableEntry>.GetInstance(); foreach (var entry in _states) { if (!entry.IsRemoved) { compacted.Add(entry.AsCached()); } } return new NodeStateTable<T>(compacted.ToImmutableAndFree(), isCompacted: true); } IStateTable IStateTable.AsCached() => AsCached(); public T Single() { Debug.Assert((_states.Length == 1 || _states.Length == 2 && _states[0].IsRemoved) && this._states[^1].Count == 1); return this._states[^1].GetItem(0); } public ImmutableArray<T> Batch() { var sourceBuilder = ArrayBuilder<T>.GetInstance(); foreach (var entry in this) { // we don't return removed entries to the downstream node. // we're creating a new state table as part of this call, so they're no longer needed if (entry.state != EntryState.Removed) { sourceBuilder.Add(entry.item); } } return sourceBuilder.ToImmutableAndFree(); } public Builder ToBuilder() { return new Builder(this); } public sealed class Builder { private readonly ArrayBuilder<TableEntry> _states; private readonly NodeStateTable<T> _previous; internal Builder(NodeStateTable<T> previous) { _states = ArrayBuilder<TableEntry>.GetInstance(); _previous = previous; } public void RemoveEntries() { // if a new table is asked to remove entries we can just do nothing // as it can't have any effect on downstream tables if (_previous._states.Length > _states.Count) { var previousEntries = _previous._states[_states.Count].AsRemoved(); _states.Add(previousEntries); } } public bool TryUseCachedEntries() { if (_previous._states.Length <= _states.Count) { return false; } var previousEntries = _previous._states[_states.Count]; Debug.Assert(previousEntries.IsCached); _states.Add(previousEntries); return true; } public bool TryUseCachedEntries(out ImmutableArray<T> entries) { if (!TryUseCachedEntries()) { entries = default; return false; } entries = _states[_states.Count - 1].ToImmutableArray(); return true; } public bool TryModifyEntry(T value, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } Debug.Assert(_previous._states[_states.Count].Count == 1); _states.Add(new TableEntry(value, comparer.Equals(_previous._states[_states.Count].GetItem(0), value) ? EntryState.Cached : EntryState.Modified)); return true; } public bool TryModifyEntries(ImmutableArray<T> outputs, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } // Semantics: // For each item in the row, we compare with the new matching new value. // - Cached when the same // - Modified when different // - Removed when old item position > outputs.length // - Added when new item position < previousTable.length var previousEntry = _previous._states[_states.Count]; // when both entries have no items, we can short circuit if (previousEntry.Count == 0 && outputs.Length == 0) { _states.Add(previousEntry); return true; } var modified = new TableEntry.Builder(); var sharedCount = Math.Min(previousEntry.Count, outputs.Length); // cached or modified items for (int i = 0; i < sharedCount; i++) { var previous = previousEntry.GetItem(i); var replacement = outputs[i]; var entryState = comparer.Equals(previous, replacement) ? EntryState.Cached : EntryState.Modified; modified.Add(replacement, entryState); } // removed for (int i = sharedCount; i < previousEntry.Count; i++) { modified.Add(previousEntry.GetItem(i), EntryState.Removed); } // added for (int i = sharedCount; i < outputs.Length; i++) { modified.Add(outputs[i], EntryState.Added); } _states.Add(modified.ToImmutableAndFree()); return true; } public void AddEntry(T value, EntryState state) { _states.Add(new TableEntry(value, state)); } public void AddEntries(ImmutableArray<T> values, EntryState state) { _states.Add(new TableEntry(values, state)); } public NodeStateTable<T> ToImmutableAndFree() { if (_states.Count == 0) { _states.Free(); return NodeStateTable<T>.Empty; } var hasNonCached = _states.Any(static s => !s.IsCached); return new NodeStateTable<T>(_states.ToImmutableAndFree(), isCompacted: !hasNonCached); } } private readonly struct TableEntry { private static readonly ImmutableArray<EntryState> s_allAddedEntries = ImmutableArray.Create(EntryState.Added); private static readonly ImmutableArray<EntryState> s_allCachedEntries = ImmutableArray.Create(EntryState.Cached); private static readonly ImmutableArray<EntryState> s_allModifiedEntries = ImmutableArray.Create(EntryState.Modified); private static readonly ImmutableArray<EntryState> s_allRemovedEntries = ImmutableArray.Create(EntryState.Removed); private readonly ImmutableArray<T> _items; private readonly T? _item; /// <summary> /// Represents the corresponding state of each item in <see cref="_items"/>, /// or contains a single state when <see cref="_item"/> is populated or when every state of <see cref="_items"/> has the same value. /// </summary> private readonly ImmutableArray<EntryState> _states; public TableEntry(T item, EntryState state) : this(item, default, GetSingleArray(state)) { } public TableEntry(ImmutableArray<T> items, EntryState state) : this(default, items, GetSingleArray(state)) { } private TableEntry(T? item, ImmutableArray<T> items, ImmutableArray<EntryState> states) { Debug.Assert(!states.IsDefault); Debug.Assert(states.Length == 1 || states.Distinct().Count() > 1); this._item = item; this._items = items; this._states = states; } public bool IsCached => this._states == s_allCachedEntries || this._states.All(s => s == EntryState.Cached); public bool IsRemoved => this._states == s_allRemovedEntries || this._states.All(s => s == EntryState.Removed); public int Count => IsSingle ? 1 : _items.Length; public T GetItem(int index) { Debug.Assert(!IsSingle || index == 0); return IsSingle ? _item : _items[index]; } public EntryState GetState(int index) => _states.Length == 1 ? _states[0] : _states[index]; public ImmutableArray<T> ToImmutableArray() => IsSingle ? ImmutableArray.Create(_item) : _items; public TableEntry AsCached() => new(_item, _items, s_allCachedEntries); public TableEntry AsRemoved() => new(_item, _items, s_allRemovedEntries); [MemberNotNullWhen(true, new[] { nameof(_item) })] private bool IsSingle => this._items.IsDefault; private static ImmutableArray<EntryState> GetSingleArray(EntryState state) => state switch { EntryState.Added => s_allAddedEntries, EntryState.Cached => s_allCachedEntries, EntryState.Modified => s_allModifiedEntries, EntryState.Removed => s_allRemovedEntries, _ => throw ExceptionUtilities.Unreachable }; #if DEBUG public override string ToString() { if (IsSingle) { return $"{GetItem(0)}: {GetState(0)}"; } else { var sb = PooledStringBuilder.GetInstance(); sb.Builder.Append("{"); for (int i = 0; i < Count; i++) { if (i > 0) { sb.Builder.Append(','); } sb.Builder.Append(" ("); sb.Builder.Append(GetItem(i)); sb.Builder.Append(':'); sb.Builder.Append(GetState(i)); sb.Builder.Append(')'); } sb.Builder.Append(" }"); return sb.ToStringAndFree(); } } #endif public sealed class Builder { private readonly ArrayBuilder<T> _items = ArrayBuilder<T>.GetInstance(); private ArrayBuilder<EntryState>? _states; private EntryState? _currentState; public void Add(T item, EntryState state) { _items.Add(item); if (!_currentState.HasValue) { _currentState = state; } else if (_states is object) { _states.Add(state); } else if (_currentState != state) { _states = ArrayBuilder<EntryState>.GetInstance(_items.Count - 1, _currentState.Value); _states.Add(state); } } public TableEntry ToImmutableAndFree() { Debug.Assert(_currentState.HasValue, "Created a builder with no values?"); return new TableEntry(item: default, _items.ToImmutableAndFree(), _states?.ToImmutableAndFree() ?? GetSingleArray(_currentState.Value)); } } } } }
1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SyntaxInputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxInputNode<T> : IIncrementalGeneratorNode<T>, ISyntaxInputNode { private readonly Func<GeneratorSyntaxContext, CancellationToken, T> _transformFunc; private readonly Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> _registerOutputAndNode; private readonly Func<SyntaxNode, CancellationToken, bool> _filterFunc; private readonly IEqualityComparer<T> _comparer; private readonly object _filterKey = new object(); internal SyntaxInputNode(Func<SyntaxNode, CancellationToken, bool> filterFunc, Func<GeneratorSyntaxContext, CancellationToken, T> transformFunc, Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> registerOutputAndNode, IEqualityComparer<T>? comparer = null) { _transformFunc = transformFunc; _registerOutputAndNode = registerOutputAndNode; _filterFunc = filterFunc; _comparer = comparer ?? EqualityComparer<T>.Default; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<T>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new SyntaxInputNode<T>(_filterFunc, _transformFunc, _registerOutputAndNode, comparer); public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutputAndNode(this, output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxInputNode<T> _owner; private readonly NodeStateTable<SyntaxNode>.Builder _filterTable; private readonly NodeStateTable<T>.Builder _transformTable; public Builder(SyntaxInputNode<T> owner, DriverStateTable table) { _owner = owner; _filterTable = table.GetStateTableOrEmpty<SyntaxNode>(_owner._filterKey).ToBuilder(); _transformTable = table.GetStateTableOrEmpty<T>(_owner).ToBuilder(); } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { tables[_owner._filterKey] = _filterTable.ToImmutableAndFree(); tables[_owner] = _transformTable.ToImmutableAndFree(); } public void VisitTree(SyntaxNode root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (state == EntryState.Removed) { // mark both syntax *and* transform nodes removed _filterTable.RemoveEntries(); _transformTable.RemoveEntries(); } else { Debug.Assert(model is object); // get the syntax nodes from cache, or a syntax walk using the filter ImmutableArray<SyntaxNode> nodes; if (state != EntryState.Cached || !_filterTable.TryUseCachedEntries(out nodes)) { nodes = IncrementalGeneratorSyntaxWalker.GetFilteredNodes(root, _owner._filterFunc, cancellationToken); _filterTable.AddEntries(nodes, EntryState.Added); } // now, using the obtained syntax nodes, run the transform foreach (var node in nodes) { var value = new GeneratorSyntaxContext(node, model); var transformed = ImmutableArray.Create(_owner._transformFunc(value, cancellationToken)); if (state == EntryState.Added || !_transformTable.TryModifyEntries(transformed, _owner._comparer)) { _transformTable.AddEntries(transformed, EntryState.Added); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal sealed class SyntaxInputNode<T> : IIncrementalGeneratorNode<T>, ISyntaxInputNode { private readonly Func<GeneratorSyntaxContext, CancellationToken, T> _transformFunc; private readonly Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> _registerOutputAndNode; private readonly Func<SyntaxNode, CancellationToken, bool> _filterFunc; private readonly IEqualityComparer<T> _comparer; private readonly object _filterKey = new object(); internal SyntaxInputNode(Func<SyntaxNode, CancellationToken, bool> filterFunc, Func<GeneratorSyntaxContext, CancellationToken, T> transformFunc, Action<ISyntaxInputNode, IIncrementalGeneratorOutputNode> registerOutputAndNode, IEqualityComparer<T>? comparer = null) { _transformFunc = transformFunc; _registerOutputAndNode = registerOutputAndNode; _filterFunc = filterFunc; _comparer = comparer ?? EqualityComparer<T>.Default; } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { return (NodeStateTable<T>)graphState.GetSyntaxInputTable(this); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new SyntaxInputNode<T>(_filterFunc, _transformFunc, _registerOutputAndNode, comparer); public ISyntaxInputBuilder GetBuilder(DriverStateTable table) => new Builder(this, table); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutputAndNode(this, output); private sealed class Builder : ISyntaxInputBuilder { private readonly SyntaxInputNode<T> _owner; private readonly NodeStateTable<SyntaxNode>.Builder _filterTable; private readonly NodeStateTable<T>.Builder _transformTable; public Builder(SyntaxInputNode<T> owner, DriverStateTable table) { _owner = owner; _filterTable = table.GetStateTableOrEmpty<SyntaxNode>(_owner._filterKey).ToBuilder(); _transformTable = table.GetStateTableOrEmpty<T>(_owner).ToBuilder(); } public ISyntaxInputNode SyntaxInputNode { get => _owner; } public void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables) { tables[_owner._filterKey] = _filterTable.ToImmutableAndFree(); tables[_owner] = _transformTable.ToImmutableAndFree(); } public void VisitTree(SyntaxNode root, EntryState state, SemanticModel? model, CancellationToken cancellationToken) { if (state == EntryState.Removed) { // mark both syntax *and* transform nodes removed _filterTable.RemoveEntries(); _transformTable.RemoveEntries(); } else { Debug.Assert(model is object); // get the syntax nodes from cache, or a syntax walk using the filter ImmutableArray<SyntaxNode> nodes; if (state != EntryState.Cached || !_filterTable.TryUseCachedEntries(out nodes)) { nodes = IncrementalGeneratorSyntaxWalker.GetFilteredNodes(root, _owner._filterFunc, cancellationToken); _filterTable.AddEntries(nodes, EntryState.Added); } // now, using the obtained syntax nodes, run the transform foreach (var node in nodes) { var value = new GeneratorSyntaxContext(node, model); var transformed = _owner._transformFunc(value, cancellationToken); if (state == EntryState.Added || !_transformTable.TryModifyEntry(transformed, _owner._comparer)) { _transformTable.AddEntry(transformed, EntryState.Added); } } } } } } }
1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, 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.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpDebugDataTipInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal readonly struct FSharpDebugDataTipInfo { internal readonly DebugDataTipInfo UnderlyingObject; public FSharpDebugDataTipInfo(TextSpan span, string text) => UnderlyingObject = new DebugDataTipInfo(span, text); public readonly TextSpan Span => UnderlyingObject.Span; public readonly string Text => UnderlyingObject.Text; public bool IsDefault => UnderlyingObject.IsDefault; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal readonly struct FSharpDebugDataTipInfo { internal readonly DebugDataTipInfo UnderlyingObject; public FSharpDebugDataTipInfo(TextSpan span, string text) => UnderlyingObject = new DebugDataTipInfo(span, text); public readonly TextSpan Span => UnderlyingObject.Span; public readonly string Text => UnderlyingObject.Text; public bool IsDefault => UnderlyingObject.IsDefault; } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceLocalSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a local variable in a method body. /// </summary> internal class SourceLocalSymbol : LocalSymbol { private readonly Binder _scopeBinder; /// <summary> /// Might not be a method symbol. /// </summary> private readonly Symbol _containingSymbol; private readonly SyntaxToken _identifierToken; private readonly ImmutableArray<Location> _locations; private readonly RefKind _refKind; private readonly TypeSyntax _typeSyntax; private readonly LocalDeclarationKind _declarationKind; private TypeWithAnnotations.Boxed _type; /// <summary> /// Scope to which the local can "escape" via aliasing/ref assignment. /// Not readonly because we can only know escape values after binding the initializer. /// </summary> protected uint _refEscapeScope; /// <summary> /// Scope to which the local's values can "escape" via ordinary assignments. /// Not readonly because we can only know escape values after binding the initializer. /// </summary> protected uint _valEscapeScope; private SourceLocalSymbol( Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind) { Debug.Assert(identifierToken.Kind() != SyntaxKind.None); Debug.Assert(declarationKind != LocalDeclarationKind.None); Debug.Assert(scopeBinder != null); this._scopeBinder = scopeBinder; this._containingSymbol = containingSymbol; this._identifierToken = identifierToken; this._typeSyntax = allowRefKind ? typeSyntax?.SkipRef(out this._refKind) : typeSyntax; this._declarationKind = declarationKind; // create this eagerly as it will always be needed for the EnsureSingleDefinition _locations = ImmutableArray.Create<Location>(identifierToken.GetLocation()); _refEscapeScope = this._refKind == RefKind.None ? scopeBinder.LocalScopeDepth : Binder.ExternalScope; // default to returnable, unless there is initializer // we do not know the type yet. // assume this is returnable in case we never get to know our type. _valEscapeScope = Binder.ExternalScope; } /// <summary> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </summary> internal Binder ScopeBinder { get { return _scopeBinder; } } internal override SyntaxNode ScopeDesignatorOpt { get { return _scopeBinder.ScopeDesignator; } } internal override uint RefEscapeScope => _refEscapeScope; internal override uint ValEscapeScope => _valEscapeScope; /// <summary> /// Binder that should be used to bind type syntax for the local. /// </summary> internal Binder TypeSyntaxBinder { get { return _scopeBinder; } // Scope binder should be good enough for this. } // When the variable's type has not yet been inferred, // don't let the debugger force inference. internal override string GetDebuggerDisplay() { return _type != null ? base.GetDebuggerDisplay() : $"{this.Kind} <var> ${this.Name}"; } public static SourceLocalSymbol MakeForeachLocal( MethodSymbol containingMethod, ForEachLoopBinder binder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection) { return new ForEachLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, collection, LocalDeclarationKind.ForEachIterationVariable); } /// <summary> /// Make a local variable symbol for an element of a deconstruction, /// which can be inferred (if necessary) by binding the enclosing statement. /// </summary> /// <param name="containingSymbol"></param> /// <param name="scopeBinder"> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </param> /// <param name="nodeBinder"> /// Enclosing binder for the location where the local is declared. /// It should be used to bind something at that location. /// </param> /// <param name="closestTypeSyntax"></param> /// <param name="identifierToken"></param> /// <param name="kind"></param> /// <param name="deconstruction"></param> /// <returns></returns> public static SourceLocalSymbol MakeDeconstructionLocal( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax closestTypeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode deconstruction) { Debug.Assert(closestTypeSyntax != null); Debug.Assert(nodeBinder != null); Debug.Assert(closestTypeSyntax.Kind() != SyntaxKind.RefType); return closestTypeSyntax.IsVar ? new DeconstructionLocalSymbol(containingSymbol, scopeBinder, nodeBinder, closestTypeSyntax, identifierToken, kind, deconstruction) : new SourceLocalSymbol(containingSymbol, scopeBinder, false, closestTypeSyntax, identifierToken, kind); } /// <summary> /// Make a local variable symbol whose type can be inferred (if necessary) by binding and enclosing construct. /// </summary> internal static LocalSymbol MakeLocalSymbolWithEnclosingContext( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) { Debug.Assert( nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel || nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer || nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer || nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm || nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) || nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || // for error recovery nodeToBind.Kind() == SyntaxKind.VariableDeclarator && new[] { SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement, SyntaxKind.FixedStatement }. Contains(nodeToBind.Ancestors().OfType<StatementSyntax>().First().Kind()) || nodeToBind is ExpressionSyntax); Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder); return typeSyntax?.IsVar != false && kind != LocalDeclarationKind.DeclarationExpressionVariable ? new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone) : new SourceLocalSymbol(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, kind); } /// <summary> /// Make a local variable symbol which can be inferred (if necessary) by binding its initializing expression. /// </summary> /// <param name="containingSymbol"></param> /// <param name="scopeBinder"> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </param> /// <param name="allowRefKind"></param> /// <param name="typeSyntax"></param> /// <param name="identifierToken"></param> /// <param name="declarationKind"></param> /// <param name="initializer"></param> /// <param name="initializerBinderOpt"> /// Binder that should be used to bind initializer, if different from the <paramref name="scopeBinder"/>. /// </param> /// <returns></returns> public static SourceLocalSymbol MakeLocal( Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, EqualsValueClauseSyntax initializer = null, Binder initializerBinderOpt = null) { Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable); return (initializer != null) ? new LocalWithInitializer(containingSymbol, scopeBinder, typeSyntax, identifierToken, initializer, initializerBinderOpt ?? scopeBinder, declarationKind) : new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind, typeSyntax, identifierToken, declarationKind); } internal override bool IsImportedFromMetadata { get { return false; } } internal override LocalDeclarationKind DeclarationKind { get { return _declarationKind; } } internal override SynthesizedLocalKind SynthesizedKind { get { return SynthesizedLocalKind.UserDefined; } } internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) { throw ExceptionUtilities.Unreachable; } internal override bool IsPinned { get { // even when dealing with "fixed" locals it is the underlying managed reference that gets pinned // the pointer variable itself is not pinned. return false; } } internal virtual void SetRefEscape(uint value) { _refEscapeScope = value; } internal virtual void SetValEscape(uint value) { _valEscapeScope = value; } public override Symbol ContainingSymbol { get { return _containingSymbol; } } /// <summary> /// Gets the name of the local variable. /// </summary> public override string Name { get { return _identifierToken.ValueText; } } // Get the identifier token that defined this local symbol. This is useful for robustly // checking if a local symbol actually matches a particular definition, even in the presence // of duplicates. internal override SyntaxToken IdentifierToken { get { return _identifierToken; } } #if DEBUG // We use this to detect infinite recursion in type inference. private int concurrentTypeResolutions = 0; #endif public override TypeWithAnnotations TypeWithAnnotations { get { if (_type == null) { #if DEBUG concurrentTypeResolutions++; Debug.Assert(concurrentTypeResolutions < 50); #endif TypeWithAnnotations localType = GetTypeSymbol(); SetTypeWithAnnotations(localType); } return _type.Value; } } public bool IsVar { get { if (_typeSyntax == null) { // in "e is {} x" there is no syntax corresponding to the type. return true; } if (_typeSyntax.IsVar) { bool isVar; TypeWithAnnotations declType = this.TypeSyntaxBinder.BindTypeOrVarKeyword(_typeSyntax, BindingDiagnosticBag.Discarded, out isVar); return isVar; } return false; } } private TypeWithAnnotations GetTypeSymbol() { // // Note that we drop the diagnostics on the floor! That is because this code is invoked mainly in // IDE scenarios where we are attempting to use the types of a variable before we have processed // the code which causes the variable's type to be inferred. In batch compilation, on the // other hand, local variables have their type inferred, if necessary, in the course of binding // the statements of a method from top to bottom, and an inferred type is given to a variable // before the variable's type is used by the compiler. // var diagnostics = BindingDiagnosticBag.Discarded; Binder typeBinder = this.TypeSyntaxBinder; bool isVar; TypeWithAnnotations declType; if (_typeSyntax == null) // In recursive patterns the type may be omitted. { isVar = true; declType = default; } else { declType = typeBinder.BindTypeOrVarKeyword(_typeSyntax.SkipRef(out _), diagnostics, out isVar); } if (isVar) { var inferredType = InferTypeOfVarVariable(diagnostics); // If we got a valid result that was not void then use the inferred type // else create an error type. if (inferredType.HasType && !inferredType.IsVoidType()) { declType = inferredType; } else { declType = TypeWithAnnotations.Create(typeBinder.CreateErrorType("var")); } } Debug.Assert(declType.HasType); return declType; } protected virtual TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { // TODO: this method must be overridden for pattern variables to bind the // expression or statement that is the nearest enclosing to the pattern variable's // declaration. That will cause the type of the pattern variable to be set as a side-effect. return _type?.Value ?? default; } internal void SetTypeWithAnnotations(TypeWithAnnotations newType) { Debug.Assert(newType.Type is object); TypeWithAnnotations? originalType = _type?.Value; // In the event that we race to set the type of a local, we should // always deduce the same type, or deduce that the type is an error. Debug.Assert((object)originalType?.DefaultType == null || originalType.Value.DefaultType.IsErrorType() && newType.Type.IsErrorType() || originalType.Value.TypeSymbolEquals(newType, TypeCompareKind.ConsiderEverything)); if ((object)_type == null) { Interlocked.CompareExchange(ref _type, new TypeWithAnnotations.Boxed(newType), null); } } /// <summary> /// Gets the locations where the local symbol was originally defined in source. /// There should not be local symbols from metadata, and there should be only one local variable declared. /// TODO: check if there are multiple same name local variables - error symbol or local symbol? /// </summary> public override ImmutableArray<Location> Locations { get { return _locations; } } internal sealed override SyntaxNode GetDeclaratorSyntax() { return _identifierToken.Parent; } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { SyntaxNode node = _identifierToken.Parent; #if DEBUG switch (_declarationKind) { case LocalDeclarationKind.RegularVariable: Debug.Assert(node is VariableDeclaratorSyntax); break; case LocalDeclarationKind.Constant: case LocalDeclarationKind.FixedVariable: case LocalDeclarationKind.UsingVariable: Debug.Assert(node is VariableDeclaratorSyntax); break; case LocalDeclarationKind.ForEachIterationVariable: Debug.Assert(node is ForEachStatementSyntax || node is SingleVariableDesignationSyntax); break; case LocalDeclarationKind.CatchVariable: Debug.Assert(node is CatchDeclarationSyntax); break; case LocalDeclarationKind.OutVariable: case LocalDeclarationKind.DeclarationExpressionVariable: case LocalDeclarationKind.DeconstructionVariable: case LocalDeclarationKind.PatternVariable: Debug.Assert(node is SingleVariableDesignationSyntax); break; default: throw ExceptionUtilities.UnexpectedValue(_declarationKind); } #endif return ImmutableArray.Create(node.GetReference()); } } internal override bool IsCompilerGenerated { get { return false; } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) { return null; } internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) { return ImmutableBindingDiagnostic<AssemblySymbol>.Empty; } public override RefKind RefKind { get { return _refKind; } } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } // If we're comparing against a symbol that was wrapped and updated for nullable, // delegate to its handling of equality, rather than our own. if (obj is UpdatedContainingSymbolAndNullableAnnotationLocal updated) { return updated.Equals(this, compareKind); } return obj is SourceLocalSymbol symbol && symbol._identifierToken.Equals(_identifierToken) && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_identifierToken.GetHashCode(), _containingSymbol.GetHashCode()); } /// <summary> /// Symbol for a local whose type can be inferred by binding its initializer. /// </summary> private sealed class LocalWithInitializer : SourceLocalSymbol { private readonly EqualsValueClauseSyntax _initializer; private readonly Binder _initializerBinder; /// <summary> /// Store the constant value and the corresponding diagnostics together /// to avoid having the former set by one thread and the latter set by /// another. /// </summary> private EvaluatedConstant _constantTuple; public LocalWithInitializer( Symbol containingSymbol, Binder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, EqualsValueClauseSyntax initializer, Binder initializerBinder, LocalDeclarationKind declarationKind) : base(containingSymbol, scopeBinder, true, typeSyntax, identifierToken, declarationKind) { Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable); Debug.Assert(initializer != null); _initializer = initializer; _initializerBinder = initializerBinder; // default to the current scope in case we need to handle self-referential error cases. _refEscapeScope = _scopeBinder.LocalScopeDepth; _valEscapeScope = _scopeBinder.LocalScopeDepth; } protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { BoundExpression initializerOpt = this._initializerBinder.BindInferredVariableInitializer(diagnostics, RefKind, _initializer, _initializer); return TypeWithAnnotations.Create(initializerOpt?.Type); } internal override SyntaxNode ForbiddenZone => _initializer; /// <summary> /// Determine the constant value of this local and the corresponding diagnostics. /// Set both to constantTuple in a single operation for thread safety. /// </summary> /// <param name="inProgress">Null for the initial call, non-null if we are in the process of evaluating a constant.</param> /// <param name="boundInitValue">If we already have the bound node for the initial value, pass it in to avoid recomputing it.</param> private void MakeConstantTuple(LocalSymbol inProgress, BoundExpression boundInitValue) { if (this.IsConst && _constantTuple == null) { var value = Microsoft.CodeAnalysis.ConstantValue.Bad; Location initValueNodeLocation = _initializer.Value.Location; var diagnostics = BindingDiagnosticBag.GetInstance(); Debug.Assert(inProgress != this); var type = this.Type; if (boundInitValue == null) { var inProgressBinder = new LocalInProgressBinder(this, this._initializerBinder); boundInitValue = inProgressBinder.BindVariableOrAutoPropInitializerValue(_initializer, this.RefKind, type, diagnostics); } value = ConstantValueUtils.GetAndValidateConstantValue(boundInitValue, this, type, initValueNodeLocation, diagnostics); Interlocked.CompareExchange(ref _constantTuple, new EvaluatedConstant(value, diagnostics.ToReadOnlyAndFree()), null); } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null) { if (this.IsConst && inProgress == this) { if (diagnostics != null) { diagnostics.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this); } return Microsoft.CodeAnalysis.ConstantValue.Bad; } MakeConstantTuple(inProgress, boundInitValue: null); return _constantTuple == null ? null : _constantTuple.Value; } internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) { Debug.Assert(boundInitValue != null); MakeConstantTuple(inProgress: null, boundInitValue: boundInitValue); return _constantTuple == null ? ImmutableBindingDiagnostic<AssemblySymbol>.Empty : _constantTuple.Diagnostics; } internal override void SetRefEscape(uint value) { Debug.Assert(value <= _refEscapeScope); _refEscapeScope = value; } internal override void SetValEscape(uint value) { Debug.Assert(value <= _valEscapeScope); _valEscapeScope = value; } } /// <summary> /// Symbol for a foreach iteration variable that can be inferred by binding the /// collection element type of the foreach. /// </summary> private sealed class ForEachLocalSymbol : SourceLocalSymbol { private readonly ExpressionSyntax _collection; public ForEachLocalSymbol( Symbol containingSymbol, ForEachLoopBinder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection, LocalDeclarationKind declarationKind) : base(containingSymbol, scopeBinder, allowRefKind: true, typeSyntax, identifierToken, declarationKind) { Debug.Assert(declarationKind == LocalDeclarationKind.ForEachIterationVariable); _collection = collection; } /// <summary> /// We initialize the base's ScopeBinder with a ForEachLoopBinder, so it is safe /// to cast it to that type here. /// </summary> private ForEachLoopBinder ForEachLoopBinder => (ForEachLoopBinder)ScopeBinder; protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { return ForEachLoopBinder.InferCollectionElementType(diagnostics, _collection); } /// <summary> /// There is no forbidden zone for a foreach loop, because the iteration /// variable is not in scope in the collection expression. /// </summary> internal override SyntaxNode ForbiddenZone => null; } /// <summary> /// Symbol for a deconstruction local that might require type inference. /// For instance, local <c>x</c> in <c>var (x, y) = ...</c> or <c>(var x, int y) = ...</c>. /// </summary> private class DeconstructionLocalSymbol : SourceLocalSymbol { private readonly SyntaxNode _deconstruction; private readonly Binder _nodeBinder; public DeconstructionLocalSymbol( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode deconstruction) : base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind) { _deconstruction = deconstruction; _nodeBinder = nodeBinder; } protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { // Try binding enclosing deconstruction-declaration (the top-level VariableDeclaration), this should force the inference. switch (_deconstruction.Kind()) { case SyntaxKind.SimpleAssignmentExpression: var assignment = (AssignmentExpressionSyntax)_deconstruction; Debug.Assert(assignment.IsDeconstruction()); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; _nodeBinder.BindDeconstruction(assignment, assignment.Left, assignment.Right, diagnostics, ref declaration, ref expression); break; case SyntaxKind.ForEachVariableStatement: Debug.Assert(this.ScopeBinder.GetBinder((ForEachVariableStatementSyntax)_deconstruction) == _nodeBinder); _nodeBinder.BindForEachDeconstruction(diagnostics, _nodeBinder); break; default: return TypeWithAnnotations.Create(_nodeBinder.CreateErrorType()); } return _type.Value; } internal override SyntaxNode ForbiddenZone { get { switch (_deconstruction.Kind()) { case SyntaxKind.SimpleAssignmentExpression: return _deconstruction; case SyntaxKind.ForEachVariableStatement: // There is no forbidden zone for a foreach statement, because the // variables are not in scope in the expression. return null; default: return null; } } } } private class LocalSymbolWithEnclosingContext : SourceLocalSymbol { private readonly SyntaxNode _forbiddenZone; private readonly Binder _nodeBinder; private readonly SyntaxNode _nodeToBind; public LocalSymbolWithEnclosingContext( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) : base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind) { Debug.Assert( nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel || nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer || nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer || nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) || nodeToBind.Kind() == SyntaxKind.VariableDeclarator || nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm || nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || nodeToBind is ExpressionSyntax); Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder); this._nodeBinder = nodeBinder; this._nodeToBind = nodeToBind; this._forbiddenZone = forbiddenZone; } internal override SyntaxNode ForbiddenZone => _forbiddenZone; // This type is currently used for out variables and pattern variables. // Pattern variables do not have a forbidden zone, so we only need to produce // the diagnostic for out variables here. internal override ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList; protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { switch (_nodeToBind.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: var initializer = (ConstructorInitializerSyntax)_nodeToBind; _nodeBinder.BindConstructorInitializer(initializer, diagnostics); break; case SyntaxKind.PrimaryConstructorBaseType: _nodeBinder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.ArgumentList: switch (_nodeToBind.Parent) { case ConstructorInitializerSyntax ctorInitializer: _nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics); break; case PrimaryConstructorBaseTypeSyntax ctorInitializer: _nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(_nodeToBind.Parent); } break; case SyntaxKind.CasePatternSwitchLabel: _nodeBinder.BindPatternSwitchLabelForInference((CasePatternSwitchLabelSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.VariableDeclarator: // This occurs, for example, in // int x, y[out var Z, 1 is int I]; // for (int x, y[out var Z, 1 is int I]; ;) {} _nodeBinder.BindDeclaratorArguments((VariableDeclaratorSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.SwitchExpressionArm: var arm = (SwitchExpressionArmSyntax)_nodeToBind; var armBinder = (SwitchExpressionArmBinder)_nodeBinder; armBinder.BindSwitchExpressionArm(arm, diagnostics); break; case SyntaxKind.GotoCaseStatement: _nodeBinder.BindStatement((GotoStatementSyntax)_nodeToBind, diagnostics); break; default: _nodeBinder.BindExpression((ExpressionSyntax)_nodeToBind, diagnostics); break; } if (this._type == null) { Debug.Assert(this.DeclarationKind == LocalDeclarationKind.DeclarationExpressionVariable); SetTypeWithAnnotations(TypeWithAnnotations.Create(_nodeBinder.CreateErrorType("var"))); } return _type.Value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a local variable in a method body. /// </summary> internal class SourceLocalSymbol : LocalSymbol { private readonly Binder _scopeBinder; /// <summary> /// Might not be a method symbol. /// </summary> private readonly Symbol _containingSymbol; private readonly SyntaxToken _identifierToken; private readonly ImmutableArray<Location> _locations; private readonly RefKind _refKind; private readonly TypeSyntax _typeSyntax; private readonly LocalDeclarationKind _declarationKind; private TypeWithAnnotations.Boxed _type; /// <summary> /// Scope to which the local can "escape" via aliasing/ref assignment. /// Not readonly because we can only know escape values after binding the initializer. /// </summary> protected uint _refEscapeScope; /// <summary> /// Scope to which the local's values can "escape" via ordinary assignments. /// Not readonly because we can only know escape values after binding the initializer. /// </summary> protected uint _valEscapeScope; private SourceLocalSymbol( Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind) { Debug.Assert(identifierToken.Kind() != SyntaxKind.None); Debug.Assert(declarationKind != LocalDeclarationKind.None); Debug.Assert(scopeBinder != null); this._scopeBinder = scopeBinder; this._containingSymbol = containingSymbol; this._identifierToken = identifierToken; this._typeSyntax = allowRefKind ? typeSyntax?.SkipRef(out this._refKind) : typeSyntax; this._declarationKind = declarationKind; // create this eagerly as it will always be needed for the EnsureSingleDefinition _locations = ImmutableArray.Create<Location>(identifierToken.GetLocation()); _refEscapeScope = this._refKind == RefKind.None ? scopeBinder.LocalScopeDepth : Binder.ExternalScope; // default to returnable, unless there is initializer // we do not know the type yet. // assume this is returnable in case we never get to know our type. _valEscapeScope = Binder.ExternalScope; } /// <summary> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </summary> internal Binder ScopeBinder { get { return _scopeBinder; } } internal override SyntaxNode ScopeDesignatorOpt { get { return _scopeBinder.ScopeDesignator; } } internal override uint RefEscapeScope => _refEscapeScope; internal override uint ValEscapeScope => _valEscapeScope; /// <summary> /// Binder that should be used to bind type syntax for the local. /// </summary> internal Binder TypeSyntaxBinder { get { return _scopeBinder; } // Scope binder should be good enough for this. } // When the variable's type has not yet been inferred, // don't let the debugger force inference. internal override string GetDebuggerDisplay() { return _type != null ? base.GetDebuggerDisplay() : $"{this.Kind} <var> ${this.Name}"; } public static SourceLocalSymbol MakeForeachLocal( MethodSymbol containingMethod, ForEachLoopBinder binder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection) { return new ForEachLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, collection, LocalDeclarationKind.ForEachIterationVariable); } /// <summary> /// Make a local variable symbol for an element of a deconstruction, /// which can be inferred (if necessary) by binding the enclosing statement. /// </summary> /// <param name="containingSymbol"></param> /// <param name="scopeBinder"> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </param> /// <param name="nodeBinder"> /// Enclosing binder for the location where the local is declared. /// It should be used to bind something at that location. /// </param> /// <param name="closestTypeSyntax"></param> /// <param name="identifierToken"></param> /// <param name="kind"></param> /// <param name="deconstruction"></param> /// <returns></returns> public static SourceLocalSymbol MakeDeconstructionLocal( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax closestTypeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode deconstruction) { Debug.Assert(closestTypeSyntax != null); Debug.Assert(nodeBinder != null); Debug.Assert(closestTypeSyntax.Kind() != SyntaxKind.RefType); return closestTypeSyntax.IsVar ? new DeconstructionLocalSymbol(containingSymbol, scopeBinder, nodeBinder, closestTypeSyntax, identifierToken, kind, deconstruction) : new SourceLocalSymbol(containingSymbol, scopeBinder, false, closestTypeSyntax, identifierToken, kind); } /// <summary> /// Make a local variable symbol whose type can be inferred (if necessary) by binding and enclosing construct. /// </summary> internal static LocalSymbol MakeLocalSymbolWithEnclosingContext( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind kind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) { Debug.Assert( nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel || nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer || nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer || nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm || nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) || nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || // for error recovery nodeToBind.Kind() == SyntaxKind.VariableDeclarator && new[] { SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement, SyntaxKind.FixedStatement }. Contains(nodeToBind.Ancestors().OfType<StatementSyntax>().First().Kind()) || nodeToBind is ExpressionSyntax); Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder); return typeSyntax?.IsVar != false && kind != LocalDeclarationKind.DeclarationExpressionVariable ? new LocalSymbolWithEnclosingContext(containingSymbol, scopeBinder, nodeBinder, typeSyntax, identifierToken, kind, nodeToBind, forbiddenZone) : new SourceLocalSymbol(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, kind); } /// <summary> /// Make a local variable symbol which can be inferred (if necessary) by binding its initializing expression. /// </summary> /// <param name="containingSymbol"></param> /// <param name="scopeBinder"> /// Binder that owns the scope for the local, the one that returns it in its <see cref="Binder.Locals"/> array. /// </param> /// <param name="allowRefKind"></param> /// <param name="typeSyntax"></param> /// <param name="identifierToken"></param> /// <param name="declarationKind"></param> /// <param name="initializer"></param> /// <param name="initializerBinderOpt"> /// Binder that should be used to bind initializer, if different from the <paramref name="scopeBinder"/>. /// </param> /// <returns></returns> public static SourceLocalSymbol MakeLocal( Symbol containingSymbol, Binder scopeBinder, bool allowRefKind, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, EqualsValueClauseSyntax initializer = null, Binder initializerBinderOpt = null) { Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable); return (initializer != null) ? new LocalWithInitializer(containingSymbol, scopeBinder, typeSyntax, identifierToken, initializer, initializerBinderOpt ?? scopeBinder, declarationKind) : new SourceLocalSymbol(containingSymbol, scopeBinder, allowRefKind, typeSyntax, identifierToken, declarationKind); } internal override bool IsImportedFromMetadata { get { return false; } } internal override LocalDeclarationKind DeclarationKind { get { return _declarationKind; } } internal override SynthesizedLocalKind SynthesizedKind { get { return SynthesizedLocalKind.UserDefined; } } internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) { throw ExceptionUtilities.Unreachable; } internal override bool IsPinned { get { // even when dealing with "fixed" locals it is the underlying managed reference that gets pinned // the pointer variable itself is not pinned. return false; } } internal virtual void SetRefEscape(uint value) { _refEscapeScope = value; } internal virtual void SetValEscape(uint value) { _valEscapeScope = value; } public override Symbol ContainingSymbol { get { return _containingSymbol; } } /// <summary> /// Gets the name of the local variable. /// </summary> public override string Name { get { return _identifierToken.ValueText; } } // Get the identifier token that defined this local symbol. This is useful for robustly // checking if a local symbol actually matches a particular definition, even in the presence // of duplicates. internal override SyntaxToken IdentifierToken { get { return _identifierToken; } } #if DEBUG // We use this to detect infinite recursion in type inference. private int concurrentTypeResolutions = 0; #endif public override TypeWithAnnotations TypeWithAnnotations { get { if (_type == null) { #if DEBUG concurrentTypeResolutions++; Debug.Assert(concurrentTypeResolutions < 50); #endif TypeWithAnnotations localType = GetTypeSymbol(); SetTypeWithAnnotations(localType); } return _type.Value; } } public bool IsVar { get { if (_typeSyntax == null) { // in "e is {} x" there is no syntax corresponding to the type. return true; } if (_typeSyntax.IsVar) { bool isVar; TypeWithAnnotations declType = this.TypeSyntaxBinder.BindTypeOrVarKeyword(_typeSyntax, BindingDiagnosticBag.Discarded, out isVar); return isVar; } return false; } } private TypeWithAnnotations GetTypeSymbol() { // // Note that we drop the diagnostics on the floor! That is because this code is invoked mainly in // IDE scenarios where we are attempting to use the types of a variable before we have processed // the code which causes the variable's type to be inferred. In batch compilation, on the // other hand, local variables have their type inferred, if necessary, in the course of binding // the statements of a method from top to bottom, and an inferred type is given to a variable // before the variable's type is used by the compiler. // var diagnostics = BindingDiagnosticBag.Discarded; Binder typeBinder = this.TypeSyntaxBinder; bool isVar; TypeWithAnnotations declType; if (_typeSyntax == null) // In recursive patterns the type may be omitted. { isVar = true; declType = default; } else { declType = typeBinder.BindTypeOrVarKeyword(_typeSyntax.SkipRef(out _), diagnostics, out isVar); } if (isVar) { var inferredType = InferTypeOfVarVariable(diagnostics); // If we got a valid result that was not void then use the inferred type // else create an error type. if (inferredType.HasType && !inferredType.IsVoidType()) { declType = inferredType; } else { declType = TypeWithAnnotations.Create(typeBinder.CreateErrorType("var")); } } Debug.Assert(declType.HasType); return declType; } protected virtual TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { // TODO: this method must be overridden for pattern variables to bind the // expression or statement that is the nearest enclosing to the pattern variable's // declaration. That will cause the type of the pattern variable to be set as a side-effect. return _type?.Value ?? default; } internal void SetTypeWithAnnotations(TypeWithAnnotations newType) { Debug.Assert(newType.Type is object); TypeWithAnnotations? originalType = _type?.Value; // In the event that we race to set the type of a local, we should // always deduce the same type, or deduce that the type is an error. Debug.Assert((object)originalType?.DefaultType == null || originalType.Value.DefaultType.IsErrorType() && newType.Type.IsErrorType() || originalType.Value.TypeSymbolEquals(newType, TypeCompareKind.ConsiderEverything)); if ((object)_type == null) { Interlocked.CompareExchange(ref _type, new TypeWithAnnotations.Boxed(newType), null); } } /// <summary> /// Gets the locations where the local symbol was originally defined in source. /// There should not be local symbols from metadata, and there should be only one local variable declared. /// TODO: check if there are multiple same name local variables - error symbol or local symbol? /// </summary> public override ImmutableArray<Location> Locations { get { return _locations; } } internal sealed override SyntaxNode GetDeclaratorSyntax() { return _identifierToken.Parent; } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { SyntaxNode node = _identifierToken.Parent; #if DEBUG switch (_declarationKind) { case LocalDeclarationKind.RegularVariable: Debug.Assert(node is VariableDeclaratorSyntax); break; case LocalDeclarationKind.Constant: case LocalDeclarationKind.FixedVariable: case LocalDeclarationKind.UsingVariable: Debug.Assert(node is VariableDeclaratorSyntax); break; case LocalDeclarationKind.ForEachIterationVariable: Debug.Assert(node is ForEachStatementSyntax || node is SingleVariableDesignationSyntax); break; case LocalDeclarationKind.CatchVariable: Debug.Assert(node is CatchDeclarationSyntax); break; case LocalDeclarationKind.OutVariable: case LocalDeclarationKind.DeclarationExpressionVariable: case LocalDeclarationKind.DeconstructionVariable: case LocalDeclarationKind.PatternVariable: Debug.Assert(node is SingleVariableDesignationSyntax); break; default: throw ExceptionUtilities.UnexpectedValue(_declarationKind); } #endif return ImmutableArray.Create(node.GetReference()); } } internal override bool IsCompilerGenerated { get { return false; } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics) { return null; } internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) { return ImmutableBindingDiagnostic<AssemblySymbol>.Empty; } public override RefKind RefKind { get { return _refKind; } } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } // If we're comparing against a symbol that was wrapped and updated for nullable, // delegate to its handling of equality, rather than our own. if (obj is UpdatedContainingSymbolAndNullableAnnotationLocal updated) { return updated.Equals(this, compareKind); } return obj is SourceLocalSymbol symbol && symbol._identifierToken.Equals(_identifierToken) && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_identifierToken.GetHashCode(), _containingSymbol.GetHashCode()); } /// <summary> /// Symbol for a local whose type can be inferred by binding its initializer. /// </summary> private sealed class LocalWithInitializer : SourceLocalSymbol { private readonly EqualsValueClauseSyntax _initializer; private readonly Binder _initializerBinder; /// <summary> /// Store the constant value and the corresponding diagnostics together /// to avoid having the former set by one thread and the latter set by /// another. /// </summary> private EvaluatedConstant _constantTuple; public LocalWithInitializer( Symbol containingSymbol, Binder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, EqualsValueClauseSyntax initializer, Binder initializerBinder, LocalDeclarationKind declarationKind) : base(containingSymbol, scopeBinder, true, typeSyntax, identifierToken, declarationKind) { Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable); Debug.Assert(initializer != null); _initializer = initializer; _initializerBinder = initializerBinder; // default to the current scope in case we need to handle self-referential error cases. _refEscapeScope = _scopeBinder.LocalScopeDepth; _valEscapeScope = _scopeBinder.LocalScopeDepth; } protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { BoundExpression initializerOpt = this._initializerBinder.BindInferredVariableInitializer(diagnostics, RefKind, _initializer, _initializer); return TypeWithAnnotations.Create(initializerOpt?.Type); } internal override SyntaxNode ForbiddenZone => _initializer; /// <summary> /// Determine the constant value of this local and the corresponding diagnostics. /// Set both to constantTuple in a single operation for thread safety. /// </summary> /// <param name="inProgress">Null for the initial call, non-null if we are in the process of evaluating a constant.</param> /// <param name="boundInitValue">If we already have the bound node for the initial value, pass it in to avoid recomputing it.</param> private void MakeConstantTuple(LocalSymbol inProgress, BoundExpression boundInitValue) { if (this.IsConst && _constantTuple == null) { var value = Microsoft.CodeAnalysis.ConstantValue.Bad; Location initValueNodeLocation = _initializer.Value.Location; var diagnostics = BindingDiagnosticBag.GetInstance(); Debug.Assert(inProgress != this); var type = this.Type; if (boundInitValue == null) { var inProgressBinder = new LocalInProgressBinder(this, this._initializerBinder); boundInitValue = inProgressBinder.BindVariableOrAutoPropInitializerValue(_initializer, this.RefKind, type, diagnostics); } value = ConstantValueUtils.GetAndValidateConstantValue(boundInitValue, this, type, initValueNodeLocation, diagnostics); Interlocked.CompareExchange(ref _constantTuple, new EvaluatedConstant(value, diagnostics.ToReadOnlyAndFree()), null); } } internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag diagnostics = null) { if (this.IsConst && inProgress == this) { if (diagnostics != null) { diagnostics.Add(ErrorCode.ERR_CircConstValue, node.GetLocation(), this); } return Microsoft.CodeAnalysis.ConstantValue.Bad; } MakeConstantTuple(inProgress, boundInitValue: null); return _constantTuple == null ? null : _constantTuple.Value; } internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) { Debug.Assert(boundInitValue != null); MakeConstantTuple(inProgress: null, boundInitValue: boundInitValue); return _constantTuple == null ? ImmutableBindingDiagnostic<AssemblySymbol>.Empty : _constantTuple.Diagnostics; } internal override void SetRefEscape(uint value) { Debug.Assert(value <= _refEscapeScope); _refEscapeScope = value; } internal override void SetValEscape(uint value) { Debug.Assert(value <= _valEscapeScope); _valEscapeScope = value; } } /// <summary> /// Symbol for a foreach iteration variable that can be inferred by binding the /// collection element type of the foreach. /// </summary> private sealed class ForEachLocalSymbol : SourceLocalSymbol { private readonly ExpressionSyntax _collection; public ForEachLocalSymbol( Symbol containingSymbol, ForEachLoopBinder scopeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, ExpressionSyntax collection, LocalDeclarationKind declarationKind) : base(containingSymbol, scopeBinder, allowRefKind: true, typeSyntax, identifierToken, declarationKind) { Debug.Assert(declarationKind == LocalDeclarationKind.ForEachIterationVariable); _collection = collection; } /// <summary> /// We initialize the base's ScopeBinder with a ForEachLoopBinder, so it is safe /// to cast it to that type here. /// </summary> private ForEachLoopBinder ForEachLoopBinder => (ForEachLoopBinder)ScopeBinder; protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { return ForEachLoopBinder.InferCollectionElementType(diagnostics, _collection); } /// <summary> /// There is no forbidden zone for a foreach loop, because the iteration /// variable is not in scope in the collection expression. /// </summary> internal override SyntaxNode ForbiddenZone => null; } /// <summary> /// Symbol for a deconstruction local that might require type inference. /// For instance, local <c>x</c> in <c>var (x, y) = ...</c> or <c>(var x, int y) = ...</c>. /// </summary> private class DeconstructionLocalSymbol : SourceLocalSymbol { private readonly SyntaxNode _deconstruction; private readonly Binder _nodeBinder; public DeconstructionLocalSymbol( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode deconstruction) : base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind) { _deconstruction = deconstruction; _nodeBinder = nodeBinder; } protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { // Try binding enclosing deconstruction-declaration (the top-level VariableDeclaration), this should force the inference. switch (_deconstruction.Kind()) { case SyntaxKind.SimpleAssignmentExpression: var assignment = (AssignmentExpressionSyntax)_deconstruction; Debug.Assert(assignment.IsDeconstruction()); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; _nodeBinder.BindDeconstruction(assignment, assignment.Left, assignment.Right, diagnostics, ref declaration, ref expression); break; case SyntaxKind.ForEachVariableStatement: Debug.Assert(this.ScopeBinder.GetBinder((ForEachVariableStatementSyntax)_deconstruction) == _nodeBinder); _nodeBinder.BindForEachDeconstruction(diagnostics, _nodeBinder); break; default: return TypeWithAnnotations.Create(_nodeBinder.CreateErrorType()); } return _type.Value; } internal override SyntaxNode ForbiddenZone { get { switch (_deconstruction.Kind()) { case SyntaxKind.SimpleAssignmentExpression: return _deconstruction; case SyntaxKind.ForEachVariableStatement: // There is no forbidden zone for a foreach statement, because the // variables are not in scope in the expression. return null; default: return null; } } } } private class LocalSymbolWithEnclosingContext : SourceLocalSymbol { private readonly SyntaxNode _forbiddenZone; private readonly Binder _nodeBinder; private readonly SyntaxNode _nodeToBind; public LocalSymbolWithEnclosingContext( Symbol containingSymbol, Binder scopeBinder, Binder nodeBinder, TypeSyntax typeSyntax, SyntaxToken identifierToken, LocalDeclarationKind declarationKind, SyntaxNode nodeToBind, SyntaxNode forbiddenZone) : base(containingSymbol, scopeBinder, false, typeSyntax, identifierToken, declarationKind) { Debug.Assert( nodeToBind.Kind() == SyntaxKind.CasePatternSwitchLabel || nodeToBind.Kind() == SyntaxKind.ThisConstructorInitializer || nodeToBind.Kind() == SyntaxKind.BaseConstructorInitializer || nodeToBind.Kind() == SyntaxKind.PrimaryConstructorBaseType || // initializer for a record constructor nodeToBind.Kind() == SyntaxKind.ArgumentList && (nodeToBind.Parent is ConstructorInitializerSyntax || nodeToBind.Parent is PrimaryConstructorBaseTypeSyntax) || nodeToBind.Kind() == SyntaxKind.VariableDeclarator || nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm || nodeToBind.Kind() == SyntaxKind.GotoCaseStatement || nodeToBind is ExpressionSyntax); Debug.Assert(!(nodeToBind.Kind() == SyntaxKind.SwitchExpressionArm) || nodeBinder is SwitchExpressionArmBinder); this._nodeBinder = nodeBinder; this._nodeToBind = nodeToBind; this._forbiddenZone = forbiddenZone; } internal override SyntaxNode ForbiddenZone => _forbiddenZone; // This type is currently used for out variables and pattern variables. // Pattern variables do not have a forbidden zone, so we only need to produce // the diagnostic for out variables here. internal override ErrorCode ForbiddenDiagnostic => ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList; protected override TypeWithAnnotations InferTypeOfVarVariable(BindingDiagnosticBag diagnostics) { switch (_nodeToBind.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: var initializer = (ConstructorInitializerSyntax)_nodeToBind; _nodeBinder.BindConstructorInitializer(initializer, diagnostics); break; case SyntaxKind.PrimaryConstructorBaseType: _nodeBinder.BindConstructorInitializer((PrimaryConstructorBaseTypeSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.ArgumentList: switch (_nodeToBind.Parent) { case ConstructorInitializerSyntax ctorInitializer: _nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics); break; case PrimaryConstructorBaseTypeSyntax ctorInitializer: _nodeBinder.BindConstructorInitializer(ctorInitializer, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(_nodeToBind.Parent); } break; case SyntaxKind.CasePatternSwitchLabel: _nodeBinder.BindPatternSwitchLabelForInference((CasePatternSwitchLabelSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.VariableDeclarator: // This occurs, for example, in // int x, y[out var Z, 1 is int I]; // for (int x, y[out var Z, 1 is int I]; ;) {} _nodeBinder.BindDeclaratorArguments((VariableDeclaratorSyntax)_nodeToBind, diagnostics); break; case SyntaxKind.SwitchExpressionArm: var arm = (SwitchExpressionArmSyntax)_nodeToBind; var armBinder = (SwitchExpressionArmBinder)_nodeBinder; armBinder.BindSwitchExpressionArm(arm, diagnostics); break; case SyntaxKind.GotoCaseStatement: _nodeBinder.BindStatement((GotoStatementSyntax)_nodeToBind, diagnostics); break; default: _nodeBinder.BindExpression((ExpressionSyntax)_nodeToBind, diagnostics); break; } if (this._type == null) { Debug.Assert(this.DeclarationKind == LocalDeclarationKind.DeclarationExpressionVariable); SetTypeWithAnnotations(TypeWithAnnotations.Create(_nodeBinder.CreateErrorType("var"))); } return _type.Value; } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Features/Core/Portable/Workspace/ICompileTimeSolutionProvider.cs
// Licensed to the .NET Foundation under one or more 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.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 interface ICompileTimeSolutionProvider : IWorkspaceService { Solution GetCompileTimeSolution(Solution designTimeSolution); } }
// Licensed to the .NET Foundation under one or more 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.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 interface ICompileTimeSolutionProvider : IWorkspaceService { Solution GetCompileTimeSolution(Solution designTimeSolution); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpBreakpointResolutionResult.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { // TODO: Should be readonly struct. internal sealed class FSharpBreakpointResolutionResult { internal readonly BreakpointResolutionResult UnderlyingObject; private FSharpBreakpointResolutionResult(BreakpointResolutionResult result) => UnderlyingObject = result; public Document Document => UnderlyingObject.Document; public TextSpan TextSpan => UnderlyingObject.TextSpan; public string? LocationNameOpt => UnderlyingObject.LocationNameOpt; public bool IsLineBreakpoint => UnderlyingObject.IsLineBreakpoint; public static FSharpBreakpointResolutionResult CreateSpanResult(Document document, TextSpan textSpan, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateSpanResult(document, textSpan, locationNameOpt)); public static FSharpBreakpointResolutionResult CreateLineResult(Document document, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateLineResult(document, locationNameOpt)); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { // TODO: Should be readonly struct. internal sealed class FSharpBreakpointResolutionResult { internal readonly BreakpointResolutionResult UnderlyingObject; private FSharpBreakpointResolutionResult(BreakpointResolutionResult result) => UnderlyingObject = result; public Document Document => UnderlyingObject.Document; public TextSpan TextSpan => UnderlyingObject.TextSpan; public string? LocationNameOpt => UnderlyingObject.LocationNameOpt; public bool IsLineBreakpoint => UnderlyingObject.IsLineBreakpoint; public static FSharpBreakpointResolutionResult CreateSpanResult(Document document, TextSpan textSpan, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateSpanResult(document, textSpan, locationNameOpt)); public static FSharpBreakpointResolutionResult CreateLineResult(Document document, string? locationNameOpt = null) => new FSharpBreakpointResolutionResult(BreakpointResolutionResult.CreateLineResult(document, locationNameOpt)); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Workspaces/Core/Portable/Workspace/Host/Metadata/FrameworkAssemblyPathResolverFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Mef; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(IFrameworkAssemblyPathResolver), ServiceLayer.Default), Shared] internal sealed class FrameworkAssemblyPathResolverFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FrameworkAssemblyPathResolverFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new Service(); private sealed class Service : IFrameworkAssemblyPathResolver { public Service() { } //public bool CanResolveType(ProjectId projectId, string assemblyName, string fullyQualifiedTypeName) //{ // return false; //} public string? ResolveAssemblyPath(ProjectId projectId, string assemblyName, string? fullyQualifiedTypeName) { // Assembly path resolution not supported at the default workspace level. return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(IFrameworkAssemblyPathResolver), ServiceLayer.Default), Shared] internal sealed class FrameworkAssemblyPathResolverFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FrameworkAssemblyPathResolverFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new Service(); private sealed class Service : IFrameworkAssemblyPathResolver { public Service() { } //public bool CanResolveType(ProjectId projectId, string assemblyName, string fullyQualifiedTypeName) //{ // return false; //} public string? ResolveAssemblyPath(ProjectId projectId, string assemblyName, string? fullyQualifiedTypeName) { // Assembly path resolution not supported at the default workspace level. return null; } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Test/Core/Platform/Custom/MetadataSignatureHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public class MetadataSignatureHelper { #region Helpers private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; private static void AppendComma(StringBuilder sb) { sb.Append(", "); } private static void RemoveTrailingComma(StringBuilder sb) { if (sb.ToString().EndsWith(", ", StringComparison.Ordinal)) { sb.Length -= 2; } } private static void AppendType(Type type, StringBuilder sb, bool showGenericConstraints = false) { if (showGenericConstraints && type.IsGenericParameter) { var typeInfo = type.GetTypeInfo(); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint)) sb.Append("class "); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) sb.Append("valuetype "); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint)) sb.Append(".ctor "); var genericConstraints = typeInfo.GetGenericParameterConstraints(); if (genericConstraints.Length > 0) { sb.Append("("); foreach (var genericConstraint in genericConstraints) { AppendType(genericConstraint, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(") "); } } sb.Append(type); } private static void AppendValue(object value, StringBuilder sb, bool includeAssignmentOperator = true) { if (value != null) { if (includeAssignmentOperator) { sb.Append(" = "); } if (value.GetType() == typeof(string)) { sb.AppendFormat("\"{0}\"", value.ToString()); } else { sb.Append(Roslyn.Test.Utilities.TestHelpers.GetCultureInvariantString(value)); } } } private static void AppendCustomAttributeData(CustomAttributeData attribute, StringBuilder sb) { sb.Append("["); AppendType(attribute.Constructor.DeclaringType, sb); sb.Append("("); foreach (var positionalArgument in attribute.ConstructorArguments) { AppendValue(positionalArgument.Value, sb, false); AppendComma(sb); } foreach (var namedArgument in attribute.NamedArguments) { sb.Append(namedArgument.MemberName); AppendValue(namedArgument.TypedValue.Value, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")]"); } private static void AppendParameterInfo(ParameterInfo parameter, StringBuilder sb) { foreach (var attribute in parameter.CustomAttributes) { // these are pseudo-custom attributes that are added by Reflection but don't appear in metadata as custom attributes: if (attribute.AttributeType != typeof(OptionalAttribute) && attribute.AttributeType != typeof(InAttribute) && attribute.AttributeType != typeof(OutAttribute) && attribute.AttributeType != typeof(MarshalAsAttribute)) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } } foreach (var modreq in parameter.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in parameter.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } int length = sb.Length; AppendParameterAttributes(sb, parameter.Attributes, all: false); if (sb.Length > length) { sb.Append(" "); } AppendType(parameter.ParameterType, sb); if (!string.IsNullOrWhiteSpace(parameter.Name)) // If this is not the 'return' parameter { sb.Append(" "); sb.Append(parameter.Name); var defaultValue = parameter.RawDefaultValue; if (defaultValue != DBNull.Value) { AppendValue(defaultValue, sb); } } } public static bool AppendParameterAttributes(StringBuilder sb, ParameterAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & ParameterAttributes.Optional) != 0) list.Add("[opt]"); if ((attributes & ParameterAttributes.In) != 0) list.Add("[in]"); if ((attributes & ParameterAttributes.Out) != 0) list.Add("[out]"); if (all) { if ((attributes & ParameterAttributes.HasFieldMarshal) != 0) list.Add("marshal"); if ((attributes & ParameterAttributes.HasDefault) != 0) list.Add("default"); } sb.Append(list.Join(" ")); return list.Count > 0; } public static bool AppendPropertyAttributes(StringBuilder sb, PropertyAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & PropertyAttributes.SpecialName) != 0) list.Add("specialname"); if ((attributes & PropertyAttributes.RTSpecialName) != 0) list.Add("rtspecialname"); if (all) { if ((attributes & PropertyAttributes.HasDefault) != 0) list.Add("default"); } sb.Append(list.Join(" ")); return list.Count > 0; } public static bool AppendEventAttributes(StringBuilder sb, EventAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & EventAttributes.SpecialName) != 0) list.Add("specialname"); if ((attributes & EventAttributes.RTSpecialName) != 0) list.Add("rtspecialname"); sb.Append(list.Join(" ")); return list.Count > 0; } public static StringBuilder AppendFieldAttributes(StringBuilder sb, FieldAttributes attributes, bool all = true) { string visibility; switch (attributes & FieldAttributes.FieldAccessMask) { case FieldAttributes.PrivateScope: visibility = "privatescope"; break; case FieldAttributes.Private: visibility = "private"; break; case FieldAttributes.FamANDAssem: visibility = "famandassem"; break; case FieldAttributes.Assembly: visibility = "assembly"; break; case FieldAttributes.Family: visibility = "family"; break; case FieldAttributes.FamORAssem: visibility = "famorassem"; break; case FieldAttributes.Public: visibility = "public"; break; default: throw new InvalidOperationException(); } sb.Append(visibility); sb.Append((attributes & FieldAttributes.Static) != 0 ? " static" : " instance"); if ((attributes & FieldAttributes.InitOnly) != 0) sb.Append(" initonly"); if ((attributes & FieldAttributes.Literal) != 0) sb.Append(" literal"); if ((attributes & FieldAttributes.NotSerialized) != 0) sb.Append(" notserialized"); if ((attributes & FieldAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & FieldAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); if (all) { if ((attributes & FieldAttributes.PinvokeImpl) != 0) sb.Append(" pinvokeimpl"); if ((attributes & FieldAttributes.HasFieldMarshal) != 0) sb.Append(" marshal"); if ((attributes & FieldAttributes.HasDefault) != 0) sb.Append(" default"); if ((attributes & FieldAttributes.HasFieldRVA) != 0) sb.Append(" rva"); } return sb; } public static StringBuilder AppendMethodAttributes(StringBuilder sb, MethodAttributes attributes, bool all = true) { string visibility; switch (attributes & MethodAttributes.MemberAccessMask) { case MethodAttributes.PrivateScope: visibility = "privatescope"; break; case MethodAttributes.Private: visibility = "private"; break; case MethodAttributes.FamANDAssem: visibility = "famandassem"; break; case MethodAttributes.Assembly: visibility = "assembly"; break; case MethodAttributes.Family: visibility = "family"; break; case MethodAttributes.FamORAssem: visibility = "famorassem"; break; case MethodAttributes.Public: visibility = "public"; break; default: throw new InvalidOperationException(); } sb.Append(visibility); if ((attributes & MethodAttributes.HideBySig) != 0) sb.Append(" hidebysig"); if ((attributes & MethodAttributes.NewSlot) != 0) sb.Append(" newslot"); if ((attributes & MethodAttributes.CheckAccessOnOverride) != 0) sb.Append(" strict"); if ((attributes & MethodAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & MethodAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); if ((attributes & MethodAttributes.RequireSecObject) != 0) sb.Append(" reqsecobj"); if ((attributes & MethodAttributes.UnmanagedExport) != 0) sb.Append(" unmanagedexp"); if ((attributes & MethodAttributes.Abstract) != 0) sb.Append(" abstract"); if ((attributes & MethodAttributes.Virtual) != 0) sb.Append(" virtual"); if ((attributes & MethodAttributes.Final) != 0) sb.Append(" final"); sb.Append((attributes & MethodAttributes.Static) != 0 ? " static" : " instance"); if (all) { if ((attributes & MethodAttributes.PinvokeImpl) != 0) sb.Append(" pinvokeimpl"); } return sb; } public static StringBuilder AppendMethodImplAttributes(StringBuilder sb, MethodImplAttributes attributes) { string codeType; switch (attributes & MethodImplAttributes.CodeTypeMask) { case MethodImplAttributes.IL: codeType = "cil"; break; case MethodImplAttributes.OPTIL: codeType = "optil"; break; case MethodImplAttributes.Runtime: codeType = "runtime"; break; case MethodImplAttributes.Native: codeType = "native"; break; default: throw new InvalidOperationException(); } sb.Append(codeType); sb.Append(" "); sb.Append((attributes & MethodImplAttributes.Unmanaged) == MethodImplAttributes.Unmanaged ? "unmanaged" : "managed"); if ((attributes & MethodImplAttributes.PreserveSig) != 0) sb.Append(" preservesig"); if ((attributes & MethodImplAttributes.ForwardRef) != 0) sb.Append(" forwardref"); if ((attributes & MethodImplAttributes.InternalCall) != 0) sb.Append(" internalcall"); if ((attributes & MethodImplAttributes.Synchronized) != 0) sb.Append(" synchronized"); if ((attributes & MethodImplAttributes.NoInlining) != 0) sb.Append(" noinlining"); if ((attributes & MethodImplAttributes.AggressiveInlining) != 0) sb.Append(" aggressiveinlining"); if ((attributes & MethodImplAttributes.NoOptimization) != 0) sb.Append(" nooptimization"); return sb; } public static StringBuilder AppendTypeAttributes(StringBuilder sb, TypeAttributes attributes) { string visibility; switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NotPublic: visibility = "private"; break; case TypeAttributes.Public: visibility = "public"; break; case TypeAttributes.NestedPrivate: visibility = "nested private"; break; case TypeAttributes.NestedFamANDAssem: visibility = "nested famandassem"; break; case TypeAttributes.NestedAssembly: visibility = "nested assembly"; break; case TypeAttributes.NestedFamily: visibility = "nested family"; break; case TypeAttributes.NestedFamORAssem: visibility = "nested famorassem"; break; case TypeAttributes.NestedPublic: visibility = "nested public"; break; default: throw new InvalidOperationException(); } string layout; switch (attributes & TypeAttributes.LayoutMask) { case TypeAttributes.AutoLayout: layout = "auto"; break; case TypeAttributes.SequentialLayout: layout = "sequential"; break; case TypeAttributes.ExplicitLayout: layout = "explicit"; break; default: throw new InvalidOperationException(); } string stringFormat; switch (attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: stringFormat = "ansi"; break; case TypeAttributes.UnicodeClass: stringFormat = "unicode"; break; case TypeAttributes.AutoClass: stringFormat = "autochar"; break; default: throw new InvalidOperationException(); } if ((attributes & TypeAttributes.Interface) != 0) sb.Append("interface "); sb.Append(visibility); if ((attributes & TypeAttributes.Abstract) != 0) sb.Append(" abstract"); sb.Append(" "); sb.Append(layout); sb.Append(" "); sb.Append(stringFormat); if ((attributes & TypeAttributes.Import) != 0) sb.Append(" import"); if ((attributes & TypeAttributes.WindowsRuntime) != 0) sb.Append(" windowsruntime"); if ((attributes & TypeAttributes.Sealed) != 0) sb.Append(" sealed"); if ((attributes & TypeAttributes.Serializable) != 0) sb.Append(" serializable"); if ((attributes & TypeAttributes.BeforeFieldInit) != 0) sb.Append(" beforefieldinit"); if ((attributes & TypeAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & TypeAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); return sb; } private static void AppendMethodInfo(MethodInfo method, StringBuilder sb) { sb.Append(".method"); foreach (var attribute in method.CustomAttributes) { sb.Append(" "); AppendCustomAttributeData(attribute, sb); } sb.Append(" "); AppendMethodAttributes(sb, method.Attributes); sb.Append(" "); AppendParameterInfo(method.ReturnParameter, sb); sb.Append(" "); sb.Append(method.Name); if (method.IsGenericMethod) { sb.Append("<"); foreach (var typeParameter in method.GetGenericArguments()) { AppendType(typeParameter, sb, true); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(">"); } sb.Append("("); foreach (var parameter in method.GetParameters()) { AppendParameterInfo(parameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(") "); AppendMethodImplAttributes(sb, method.GetMethodImplementationFlags()); } private static void AppendConstructorInfo(ConstructorInfo constructor, StringBuilder sb) { sb.Append(".method"); foreach (var attribute in constructor.CustomAttributes) { sb.Append(" "); AppendCustomAttributeData(attribute, sb); } sb.Append(" "); AppendMethodAttributes(sb, constructor.Attributes); sb.Append(" "); sb.Append("void "); sb.Append(constructor.Name); if (constructor.IsGenericMethod) { sb.Append("<"); foreach (var typeParameter in constructor.GetGenericArguments()) { AppendType(typeParameter, sb, true); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(">"); } sb.Append("("); foreach (var parameter in constructor.GetParameters()) { AppendParameterInfo(parameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")"); var implFlags = constructor.GetMethodImplementationFlags(); if (implFlags.HasFlag(MethodImplAttributes.IL)) sb.Append(" cil"); if (implFlags.HasFlag(MethodImplAttributes.ForwardRef)) sb.Append(" forwardref"); if (implFlags.HasFlag(MethodImplAttributes.InternalCall)) sb.Append(" internalcall"); if (implFlags.HasFlag(MethodImplAttributes.Managed)) sb.Append(" managed"); if (implFlags.HasFlag(MethodImplAttributes.Native)) sb.Append(" native"); if (implFlags.HasFlag(MethodImplAttributes.NoInlining)) sb.Append(" noinlining"); if (implFlags.HasFlag(MethodImplAttributes.NoOptimization)) sb.Append(" nooptimization"); if (implFlags.HasFlag(MethodImplAttributes.OPTIL)) sb.Append(" optil"); if (implFlags.HasFlag(MethodImplAttributes.PreserveSig)) sb.Append(" preservesig"); if (implFlags.HasFlag(MethodImplAttributes.Runtime)) sb.Append(" runtime"); if (implFlags.HasFlag(MethodImplAttributes.Synchronized)) sb.Append(" synchronized"); if (implFlags.HasFlag(MethodImplAttributes.Unmanaged)) sb.Append(" unmanaged"); } private static void AppendPropertyInfo(PropertyInfo property, StringBuilder sb) { sb.Append(".property "); foreach (var attribute in property.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } foreach (var modreq in property.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in property.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } if (property.CanRead && property.CanWrite) { sb.Append("readwrite "); } else if (property.CanRead) { sb.Append("readonly "); } else if (property.CanWrite) { sb.Append("writeonly "); } if (property.Attributes.HasFlag(PropertyAttributes.SpecialName)) sb.Append("specialname "); if (property.Attributes.HasFlag(PropertyAttributes.RTSpecialName)) sb.Append("rtspecialname "); var propertyAccessors = property.GetAccessors(); if (propertyAccessors.Length > 0) { sb.Append(propertyAccessors[0].IsStatic ? "static " : "instance "); } AppendType(property.PropertyType, sb); sb.Append(" "); sb.Append(property.Name); var indexParameters = property.GetIndexParameters(); if (indexParameters.Length > 0) { sb.Append("("); foreach (var indexParameter in indexParameters) { AppendParameterInfo(indexParameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")"); } } private static void AppendFieldInfo(FieldInfo field, StringBuilder sb) { sb.Append(".field "); foreach (var attribute in field.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } foreach (var modreq in field.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in field.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } if (field.IsPrivate) sb.Append("private "); if (field.IsPublic) sb.Append("public "); if (field.IsFamily) sb.Append("family "); if (field.IsAssembly) sb.Append("assembly "); if (field.IsFamilyOrAssembly) sb.Append("famorassem "); if (field.IsFamilyAndAssembly) sb.Append("famandassem "); if (field.IsInitOnly) sb.Append("initonly "); if (field.IsLiteral) sb.Append("literal "); if (field.IsNotSerialized) sb.Append("notserialized "); if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) sb.Append("specialname "); if (field.Attributes.HasFlag(FieldAttributes.RTSpecialName)) sb.Append("rtspecialname "); if (field.IsPinvokeImpl) sb.Append("pinvokeimpl "); sb.Append(field.IsStatic ? "static " : "instance "); AppendType(field.FieldType, sb); sb.Append(" "); sb.Append(field.Name); if (field.IsLiteral) { AppendValue(field.GetRawConstantValue(), sb); } } private static void AppendEventInfo(EventInfo @event, StringBuilder sb) { sb.Append(".event "); foreach (var attribute in @event.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } if (@event.Attributes.HasFlag(EventAttributes.SpecialName)) sb.Append("specialname "); if (@event.Attributes.HasFlag(EventAttributes.RTSpecialName)) sb.Append("rtspecialname "); AppendType(@event.EventHandlerType, sb); sb.Append(" "); sb.Append(@event.Name); } #endregion public static IEnumerable<string> GetMemberSignatures(System.Reflection.Assembly assembly, string fullyQualifiedTypeName) { var candidates = new List<string>(); var sb = new StringBuilder(); var type = assembly.GetType(fullyQualifiedTypeName); if (type != null) { foreach (var constructor in type.GetConstructors(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendConstructorInfo(constructor, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var method in type.GetMethods(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendMethodInfo(method, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var property in type.GetProperties(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendPropertyInfo(property, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var @event in type.GetEvents(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendEventInfo(@event, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var field in type.GetFields(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendFieldInfo(field, sb); candidates.Add(sb.ToString()); sb.Clear(); } } return candidates; } public static IEnumerable<string> GetMemberSignatures(System.Reflection.Assembly assembly, string fullyQualifiedTypeName, string memberName) { IEnumerable<string> retVal = null; if (string.IsNullOrWhiteSpace(memberName)) { retVal = GetMemberSignatures(assembly, fullyQualifiedTypeName); } else { var sb = new StringBuilder(); var type = assembly.GetType(fullyQualifiedTypeName); var candidates = new SortedSet<string>(); if (type != null) { foreach (var constructor in type.GetConstructors(BINDING_FLAGS)) { if (constructor.Name == memberName) { AppendConstructorInfo(constructor, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var method in type.GetMethods(BINDING_FLAGS)) { if (method.Name == memberName) { AppendMethodInfo(method, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var property in type.GetProperties(BINDING_FLAGS)) { if (property.Name == memberName) { AppendPropertyInfo(property, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var @event in type.GetEvents(BINDING_FLAGS)) { if (@event.Name == memberName) { AppendEventInfo(@event, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var field in type.GetFields(BINDING_FLAGS)) { if (field.Name == memberName) { AppendFieldInfo(field, sb); candidates.Add(sb.ToString()); sb.Clear(); } } } retVal = candidates; } return retVal; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public class MetadataSignatureHelper { #region Helpers private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; private static void AppendComma(StringBuilder sb) { sb.Append(", "); } private static void RemoveTrailingComma(StringBuilder sb) { if (sb.ToString().EndsWith(", ", StringComparison.Ordinal)) { sb.Length -= 2; } } private static void AppendType(Type type, StringBuilder sb, bool showGenericConstraints = false) { if (showGenericConstraints && type.IsGenericParameter) { var typeInfo = type.GetTypeInfo(); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint)) sb.Append("class "); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint)) sb.Append("valuetype "); if (typeInfo.GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint)) sb.Append(".ctor "); var genericConstraints = typeInfo.GetGenericParameterConstraints(); if (genericConstraints.Length > 0) { sb.Append("("); foreach (var genericConstraint in genericConstraints) { AppendType(genericConstraint, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(") "); } } sb.Append(type); } private static void AppendValue(object value, StringBuilder sb, bool includeAssignmentOperator = true) { if (value != null) { if (includeAssignmentOperator) { sb.Append(" = "); } if (value.GetType() == typeof(string)) { sb.AppendFormat("\"{0}\"", value.ToString()); } else { sb.Append(Roslyn.Test.Utilities.TestHelpers.GetCultureInvariantString(value)); } } } private static void AppendCustomAttributeData(CustomAttributeData attribute, StringBuilder sb) { sb.Append("["); AppendType(attribute.Constructor.DeclaringType, sb); sb.Append("("); foreach (var positionalArgument in attribute.ConstructorArguments) { AppendValue(positionalArgument.Value, sb, false); AppendComma(sb); } foreach (var namedArgument in attribute.NamedArguments) { sb.Append(namedArgument.MemberName); AppendValue(namedArgument.TypedValue.Value, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")]"); } private static void AppendParameterInfo(ParameterInfo parameter, StringBuilder sb) { foreach (var attribute in parameter.CustomAttributes) { // these are pseudo-custom attributes that are added by Reflection but don't appear in metadata as custom attributes: if (attribute.AttributeType != typeof(OptionalAttribute) && attribute.AttributeType != typeof(InAttribute) && attribute.AttributeType != typeof(OutAttribute) && attribute.AttributeType != typeof(MarshalAsAttribute)) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } } foreach (var modreq in parameter.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in parameter.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } int length = sb.Length; AppendParameterAttributes(sb, parameter.Attributes, all: false); if (sb.Length > length) { sb.Append(" "); } AppendType(parameter.ParameterType, sb); if (!string.IsNullOrWhiteSpace(parameter.Name)) // If this is not the 'return' parameter { sb.Append(" "); sb.Append(parameter.Name); var defaultValue = parameter.RawDefaultValue; if (defaultValue != DBNull.Value) { AppendValue(defaultValue, sb); } } } public static bool AppendParameterAttributes(StringBuilder sb, ParameterAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & ParameterAttributes.Optional) != 0) list.Add("[opt]"); if ((attributes & ParameterAttributes.In) != 0) list.Add("[in]"); if ((attributes & ParameterAttributes.Out) != 0) list.Add("[out]"); if (all) { if ((attributes & ParameterAttributes.HasFieldMarshal) != 0) list.Add("marshal"); if ((attributes & ParameterAttributes.HasDefault) != 0) list.Add("default"); } sb.Append(list.Join(" ")); return list.Count > 0; } public static bool AppendPropertyAttributes(StringBuilder sb, PropertyAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & PropertyAttributes.SpecialName) != 0) list.Add("specialname"); if ((attributes & PropertyAttributes.RTSpecialName) != 0) list.Add("rtspecialname"); if (all) { if ((attributes & PropertyAttributes.HasDefault) != 0) list.Add("default"); } sb.Append(list.Join(" ")); return list.Count > 0; } public static bool AppendEventAttributes(StringBuilder sb, EventAttributes attributes, bool all = true) { List<string> list = new List<string>(); if ((attributes & EventAttributes.SpecialName) != 0) list.Add("specialname"); if ((attributes & EventAttributes.RTSpecialName) != 0) list.Add("rtspecialname"); sb.Append(list.Join(" ")); return list.Count > 0; } public static StringBuilder AppendFieldAttributes(StringBuilder sb, FieldAttributes attributes, bool all = true) { string visibility; switch (attributes & FieldAttributes.FieldAccessMask) { case FieldAttributes.PrivateScope: visibility = "privatescope"; break; case FieldAttributes.Private: visibility = "private"; break; case FieldAttributes.FamANDAssem: visibility = "famandassem"; break; case FieldAttributes.Assembly: visibility = "assembly"; break; case FieldAttributes.Family: visibility = "family"; break; case FieldAttributes.FamORAssem: visibility = "famorassem"; break; case FieldAttributes.Public: visibility = "public"; break; default: throw new InvalidOperationException(); } sb.Append(visibility); sb.Append((attributes & FieldAttributes.Static) != 0 ? " static" : " instance"); if ((attributes & FieldAttributes.InitOnly) != 0) sb.Append(" initonly"); if ((attributes & FieldAttributes.Literal) != 0) sb.Append(" literal"); if ((attributes & FieldAttributes.NotSerialized) != 0) sb.Append(" notserialized"); if ((attributes & FieldAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & FieldAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); if (all) { if ((attributes & FieldAttributes.PinvokeImpl) != 0) sb.Append(" pinvokeimpl"); if ((attributes & FieldAttributes.HasFieldMarshal) != 0) sb.Append(" marshal"); if ((attributes & FieldAttributes.HasDefault) != 0) sb.Append(" default"); if ((attributes & FieldAttributes.HasFieldRVA) != 0) sb.Append(" rva"); } return sb; } public static StringBuilder AppendMethodAttributes(StringBuilder sb, MethodAttributes attributes, bool all = true) { string visibility; switch (attributes & MethodAttributes.MemberAccessMask) { case MethodAttributes.PrivateScope: visibility = "privatescope"; break; case MethodAttributes.Private: visibility = "private"; break; case MethodAttributes.FamANDAssem: visibility = "famandassem"; break; case MethodAttributes.Assembly: visibility = "assembly"; break; case MethodAttributes.Family: visibility = "family"; break; case MethodAttributes.FamORAssem: visibility = "famorassem"; break; case MethodAttributes.Public: visibility = "public"; break; default: throw new InvalidOperationException(); } sb.Append(visibility); if ((attributes & MethodAttributes.HideBySig) != 0) sb.Append(" hidebysig"); if ((attributes & MethodAttributes.NewSlot) != 0) sb.Append(" newslot"); if ((attributes & MethodAttributes.CheckAccessOnOverride) != 0) sb.Append(" strict"); if ((attributes & MethodAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & MethodAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); if ((attributes & MethodAttributes.RequireSecObject) != 0) sb.Append(" reqsecobj"); if ((attributes & MethodAttributes.UnmanagedExport) != 0) sb.Append(" unmanagedexp"); if ((attributes & MethodAttributes.Abstract) != 0) sb.Append(" abstract"); if ((attributes & MethodAttributes.Virtual) != 0) sb.Append(" virtual"); if ((attributes & MethodAttributes.Final) != 0) sb.Append(" final"); sb.Append((attributes & MethodAttributes.Static) != 0 ? " static" : " instance"); if (all) { if ((attributes & MethodAttributes.PinvokeImpl) != 0) sb.Append(" pinvokeimpl"); } return sb; } public static StringBuilder AppendMethodImplAttributes(StringBuilder sb, MethodImplAttributes attributes) { string codeType; switch (attributes & MethodImplAttributes.CodeTypeMask) { case MethodImplAttributes.IL: codeType = "cil"; break; case MethodImplAttributes.OPTIL: codeType = "optil"; break; case MethodImplAttributes.Runtime: codeType = "runtime"; break; case MethodImplAttributes.Native: codeType = "native"; break; default: throw new InvalidOperationException(); } sb.Append(codeType); sb.Append(" "); sb.Append((attributes & MethodImplAttributes.Unmanaged) == MethodImplAttributes.Unmanaged ? "unmanaged" : "managed"); if ((attributes & MethodImplAttributes.PreserveSig) != 0) sb.Append(" preservesig"); if ((attributes & MethodImplAttributes.ForwardRef) != 0) sb.Append(" forwardref"); if ((attributes & MethodImplAttributes.InternalCall) != 0) sb.Append(" internalcall"); if ((attributes & MethodImplAttributes.Synchronized) != 0) sb.Append(" synchronized"); if ((attributes & MethodImplAttributes.NoInlining) != 0) sb.Append(" noinlining"); if ((attributes & MethodImplAttributes.AggressiveInlining) != 0) sb.Append(" aggressiveinlining"); if ((attributes & MethodImplAttributes.NoOptimization) != 0) sb.Append(" nooptimization"); return sb; } public static StringBuilder AppendTypeAttributes(StringBuilder sb, TypeAttributes attributes) { string visibility; switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NotPublic: visibility = "private"; break; case TypeAttributes.Public: visibility = "public"; break; case TypeAttributes.NestedPrivate: visibility = "nested private"; break; case TypeAttributes.NestedFamANDAssem: visibility = "nested famandassem"; break; case TypeAttributes.NestedAssembly: visibility = "nested assembly"; break; case TypeAttributes.NestedFamily: visibility = "nested family"; break; case TypeAttributes.NestedFamORAssem: visibility = "nested famorassem"; break; case TypeAttributes.NestedPublic: visibility = "nested public"; break; default: throw new InvalidOperationException(); } string layout; switch (attributes & TypeAttributes.LayoutMask) { case TypeAttributes.AutoLayout: layout = "auto"; break; case TypeAttributes.SequentialLayout: layout = "sequential"; break; case TypeAttributes.ExplicitLayout: layout = "explicit"; break; default: throw new InvalidOperationException(); } string stringFormat; switch (attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: stringFormat = "ansi"; break; case TypeAttributes.UnicodeClass: stringFormat = "unicode"; break; case TypeAttributes.AutoClass: stringFormat = "autochar"; break; default: throw new InvalidOperationException(); } if ((attributes & TypeAttributes.Interface) != 0) sb.Append("interface "); sb.Append(visibility); if ((attributes & TypeAttributes.Abstract) != 0) sb.Append(" abstract"); sb.Append(" "); sb.Append(layout); sb.Append(" "); sb.Append(stringFormat); if ((attributes & TypeAttributes.Import) != 0) sb.Append(" import"); if ((attributes & TypeAttributes.WindowsRuntime) != 0) sb.Append(" windowsruntime"); if ((attributes & TypeAttributes.Sealed) != 0) sb.Append(" sealed"); if ((attributes & TypeAttributes.Serializable) != 0) sb.Append(" serializable"); if ((attributes & TypeAttributes.BeforeFieldInit) != 0) sb.Append(" beforefieldinit"); if ((attributes & TypeAttributes.SpecialName) != 0) sb.Append(" specialname"); if ((attributes & TypeAttributes.RTSpecialName) != 0) sb.Append(" rtspecialname"); return sb; } private static void AppendMethodInfo(MethodInfo method, StringBuilder sb) { sb.Append(".method"); foreach (var attribute in method.CustomAttributes) { sb.Append(" "); AppendCustomAttributeData(attribute, sb); } sb.Append(" "); AppendMethodAttributes(sb, method.Attributes); sb.Append(" "); AppendParameterInfo(method.ReturnParameter, sb); sb.Append(" "); sb.Append(method.Name); if (method.IsGenericMethod) { sb.Append("<"); foreach (var typeParameter in method.GetGenericArguments()) { AppendType(typeParameter, sb, true); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(">"); } sb.Append("("); foreach (var parameter in method.GetParameters()) { AppendParameterInfo(parameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(") "); AppendMethodImplAttributes(sb, method.GetMethodImplementationFlags()); } private static void AppendConstructorInfo(ConstructorInfo constructor, StringBuilder sb) { sb.Append(".method"); foreach (var attribute in constructor.CustomAttributes) { sb.Append(" "); AppendCustomAttributeData(attribute, sb); } sb.Append(" "); AppendMethodAttributes(sb, constructor.Attributes); sb.Append(" "); sb.Append("void "); sb.Append(constructor.Name); if (constructor.IsGenericMethod) { sb.Append("<"); foreach (var typeParameter in constructor.GetGenericArguments()) { AppendType(typeParameter, sb, true); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(">"); } sb.Append("("); foreach (var parameter in constructor.GetParameters()) { AppendParameterInfo(parameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")"); var implFlags = constructor.GetMethodImplementationFlags(); if (implFlags.HasFlag(MethodImplAttributes.IL)) sb.Append(" cil"); if (implFlags.HasFlag(MethodImplAttributes.ForwardRef)) sb.Append(" forwardref"); if (implFlags.HasFlag(MethodImplAttributes.InternalCall)) sb.Append(" internalcall"); if (implFlags.HasFlag(MethodImplAttributes.Managed)) sb.Append(" managed"); if (implFlags.HasFlag(MethodImplAttributes.Native)) sb.Append(" native"); if (implFlags.HasFlag(MethodImplAttributes.NoInlining)) sb.Append(" noinlining"); if (implFlags.HasFlag(MethodImplAttributes.NoOptimization)) sb.Append(" nooptimization"); if (implFlags.HasFlag(MethodImplAttributes.OPTIL)) sb.Append(" optil"); if (implFlags.HasFlag(MethodImplAttributes.PreserveSig)) sb.Append(" preservesig"); if (implFlags.HasFlag(MethodImplAttributes.Runtime)) sb.Append(" runtime"); if (implFlags.HasFlag(MethodImplAttributes.Synchronized)) sb.Append(" synchronized"); if (implFlags.HasFlag(MethodImplAttributes.Unmanaged)) sb.Append(" unmanaged"); } private static void AppendPropertyInfo(PropertyInfo property, StringBuilder sb) { sb.Append(".property "); foreach (var attribute in property.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } foreach (var modreq in property.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in property.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } if (property.CanRead && property.CanWrite) { sb.Append("readwrite "); } else if (property.CanRead) { sb.Append("readonly "); } else if (property.CanWrite) { sb.Append("writeonly "); } if (property.Attributes.HasFlag(PropertyAttributes.SpecialName)) sb.Append("specialname "); if (property.Attributes.HasFlag(PropertyAttributes.RTSpecialName)) sb.Append("rtspecialname "); var propertyAccessors = property.GetAccessors(); if (propertyAccessors.Length > 0) { sb.Append(propertyAccessors[0].IsStatic ? "static " : "instance "); } AppendType(property.PropertyType, sb); sb.Append(" "); sb.Append(property.Name); var indexParameters = property.GetIndexParameters(); if (indexParameters.Length > 0) { sb.Append("("); foreach (var indexParameter in indexParameters) { AppendParameterInfo(indexParameter, sb); AppendComma(sb); } RemoveTrailingComma(sb); sb.Append(")"); } } private static void AppendFieldInfo(FieldInfo field, StringBuilder sb) { sb.Append(".field "); foreach (var attribute in field.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } foreach (var modreq in field.GetRequiredCustomModifiers()) { sb.Append("modreq("); AppendType(modreq, sb); sb.Append(") "); } foreach (var modopt in field.GetOptionalCustomModifiers()) { sb.Append("modopt("); AppendType(modopt, sb); sb.Append(") "); } if (field.IsPrivate) sb.Append("private "); if (field.IsPublic) sb.Append("public "); if (field.IsFamily) sb.Append("family "); if (field.IsAssembly) sb.Append("assembly "); if (field.IsFamilyOrAssembly) sb.Append("famorassem "); if (field.IsFamilyAndAssembly) sb.Append("famandassem "); if (field.IsInitOnly) sb.Append("initonly "); if (field.IsLiteral) sb.Append("literal "); if (field.IsNotSerialized) sb.Append("notserialized "); if (field.Attributes.HasFlag(FieldAttributes.SpecialName)) sb.Append("specialname "); if (field.Attributes.HasFlag(FieldAttributes.RTSpecialName)) sb.Append("rtspecialname "); if (field.IsPinvokeImpl) sb.Append("pinvokeimpl "); sb.Append(field.IsStatic ? "static " : "instance "); AppendType(field.FieldType, sb); sb.Append(" "); sb.Append(field.Name); if (field.IsLiteral) { AppendValue(field.GetRawConstantValue(), sb); } } private static void AppendEventInfo(EventInfo @event, StringBuilder sb) { sb.Append(".event "); foreach (var attribute in @event.CustomAttributes) { AppendCustomAttributeData(attribute, sb); sb.Append(" "); } if (@event.Attributes.HasFlag(EventAttributes.SpecialName)) sb.Append("specialname "); if (@event.Attributes.HasFlag(EventAttributes.RTSpecialName)) sb.Append("rtspecialname "); AppendType(@event.EventHandlerType, sb); sb.Append(" "); sb.Append(@event.Name); } #endregion public static IEnumerable<string> GetMemberSignatures(System.Reflection.Assembly assembly, string fullyQualifiedTypeName) { var candidates = new List<string>(); var sb = new StringBuilder(); var type = assembly.GetType(fullyQualifiedTypeName); if (type != null) { foreach (var constructor in type.GetConstructors(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendConstructorInfo(constructor, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var method in type.GetMethods(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendMethodInfo(method, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var property in type.GetProperties(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendPropertyInfo(property, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var @event in type.GetEvents(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendEventInfo(@event, sb); candidates.Add(sb.ToString()); sb.Clear(); } foreach (var field in type.GetFields(BINDING_FLAGS).OrderBy((member) => member.Name)) { AppendFieldInfo(field, sb); candidates.Add(sb.ToString()); sb.Clear(); } } return candidates; } public static IEnumerable<string> GetMemberSignatures(System.Reflection.Assembly assembly, string fullyQualifiedTypeName, string memberName) { IEnumerable<string> retVal = null; if (string.IsNullOrWhiteSpace(memberName)) { retVal = GetMemberSignatures(assembly, fullyQualifiedTypeName); } else { var sb = new StringBuilder(); var type = assembly.GetType(fullyQualifiedTypeName); var candidates = new SortedSet<string>(); if (type != null) { foreach (var constructor in type.GetConstructors(BINDING_FLAGS)) { if (constructor.Name == memberName) { AppendConstructorInfo(constructor, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var method in type.GetMethods(BINDING_FLAGS)) { if (method.Name == memberName) { AppendMethodInfo(method, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var property in type.GetProperties(BINDING_FLAGS)) { if (property.Name == memberName) { AppendPropertyInfo(property, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var @event in type.GetEvents(BINDING_FLAGS)) { if (@event.Name == memberName) { AppendEventInfo(@event, sb); candidates.Add(sb.ToString()); sb.Clear(); } } foreach (var field in type.GetFields(BINDING_FLAGS)) { if (field.Name == memberName) { AppendFieldInfo(field, sb); candidates.Add(sb.ToString()); sb.Clear(); } } } retVal = candidates; } return retVal; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/Test/MetadataAsSource/MetadataAsSourceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests : AbstractMetadataAsSourceTests { public enum OriginatingProjectLanguage { CSharp, VisualBasic, } private static string ToLanguageName(OriginatingProjectLanguage language) => language switch { OriginatingProjectLanguage.CSharp => LanguageNames.CSharp, OriginatingProjectLanguage.VisualBasic => LanguageNames.VisualBasic, _ => throw ExceptionUtilities.UnexpectedValue(language), }; [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestClass(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546241")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInterface(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public interface I {}"; var symbolName = "I"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public interface [|I|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Interface [|I|] End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|I|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|I|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestConstructor(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C {}"; var symbolName = "C..ctor"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public [|C|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub [|New|]() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestMethod(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public void Goo() {} }"; var symbolName = "C.Goo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public void [|Goo|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Sub [|Goo|]() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public void [|Goo|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public void [|Goo|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public string S; }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public string [|S|]; public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public [|S|] As String Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546240")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestProperty(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public string S { get; protected set; } }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|S|] {{ get; protected set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Property [|S|] As String End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|] {{ get; protected set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|] {{ get; protected set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546194")] [WorkItem(546291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546291")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "using System; public class C { public event Action E; }"; var symbolName = "C.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public class C {{ public C(); public event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Public Class C Public Sub New() Public Event [|E|] As Action End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public class C {{ public event Action [|E|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public class C {{ public event Action [|E|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNestedType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { protected class D { } }"; var symbolName = "C+D"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); protected class [|D|] {{ public D(); }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Protected Class [|D|] Public Sub New() End Class End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ protected class [|D|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ protected class [|D|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnum(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E { A, B, C }"; var symbolName = "E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum [|E|] {{ A = 0, B = 1, C = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum [|E|] A = 0 B = 1 C = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum [|E|] {{ A, B, C }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum [|E|] {{ A, B, C }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumFromField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E { A, B, C }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E {{ A = 0, B = 1, [|C|] = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E A = 0 B = 1 [|C|] = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546273")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithUnderlyingType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A = 0, B = 1, [|C|] = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A = 0 B = 1 [|C|] = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(650741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650741")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithOverflowingUnderlyingType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : ulong { A = 9223372036854775808 }"; var symbolName = "E.A"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : ulong {{ [|A|] = 9223372036854775808 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As ULong [|A|] = 9223372036854775808UL End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : ulong {{ [|A|] = 9223372036854775808uL }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : ulong {{ [|A|] = 9223372036854775808uL }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithDifferentValues(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A = 1, B = 2, [|C|] = 3 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A = 1 B = 2 [|C|] = 3 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A = 1, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A = 1, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInNamespace(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "namespace N { public class C {} }"; var symbolName = "N.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Namespace N Public Class [|C|] Public Sub New() End Class End Namespace", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion namespace N {{ public class [|C|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion namespace N {{ public class [|C|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace1() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N; public class [|C|] {{ public C(); }}"); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace2() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "9"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}"); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace3() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}"); } [WorkItem(546223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546223")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInlineConstant(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"public class C { public const string S = ""Hello mas""; }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public const string [|S|] = ""Hello mas""; public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Const [|S|] As String = ""Hello mas"" Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public const string [|S|] = ""Hello mas""; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public const string [|S|] = ""Hello mas""; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546221")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInlineTypeOf(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System; public class MyTypeAttribute : Attribute { public MyTypeAttribute(Type type) {} } [MyType(typeof(string))] public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [MyType(typeof(string))] public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <MyType(GetType(String))> Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion [MyType(typeof(string))] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion [MyType(typeof(string))] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546231")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNoDefaultConstructorInStructs(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public struct S {}"; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReferenceDefinedType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public static C Create() { return new C(); } }"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public static C Create(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() Public Shared Function Create() As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public static C Create() {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public static C Create() {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestGenericType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class G<SomeType> { public SomeType S; }"; var symbolName = "G`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|G|]<SomeType> {{ public SomeType S; public G(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|G|](Of SomeType) Public S As SomeType Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|G|]<SomeType> {{ public SomeType S; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|G|]<SomeType> {{ public SomeType S; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(38916, "https://github.com/dotnet/roslyn/issues/38916")] public async Task TestParameterAttributes(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public class C<[My] T> { public void Method([My] T x, [My] T y) { } } internal class MyAttribute : System.Attribute { } "; var symbolName = "C`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|]<[MyAttribute] T> {{ public C(); public void Method([MyAttribute] T x, [MyAttribute] T y); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|](Of T) Public Sub New() Public Sub Method(<MyAttribute> x As T, <MyAttribute> y As T) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|]<[My] T> {{ public void Method([My] T x, [My] T y) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|]<[My] T> {{ public void Method([My] T x, [My] T y) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(38916, "https://github.com/dotnet/roslyn/issues/38916")] public async Task TestGenericWithNullableReferenceTypes(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" #nullable enable public interface C<T> { bool Equals([AllowNull] T other); } internal class AllowNullAttribute : System.Attribute { } "; var symbolName = "C`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public interface [|C|]<T> {{ bool Equals([AllowNullAttribute] T other); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <NullableContextAttribute(1)> Public Interface [|C|](Of T) Function Equals(<AllowNullAttribute> other As T) As Boolean End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|C|]<T> {{ bool Equals([AllowNull] T other); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|C|]<T> {{ bool Equals([AllowNull] T other); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestGenericDelegate(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public delegate void D<SomeType>(SomeType s); }"; var symbolName = "C+D`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public delegate void [|D|]<SomeType>(SomeType s); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Delegate Sub [|D|](Of SomeType)(s As SomeType) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public delegate void [|D|]<SomeType>(SomeType s); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public delegate void [|D|]<SomeType>(SomeType s); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546200, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546200")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestAttribute(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System; namespace N { public class WorkingAttribute : Attribute { public WorkingAttribute(bool working) {} } } [N.Working(true)] public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using N; [Working(true)] public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports N <Working(True)> Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using N; [Working(true)] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using N; [Working(true)] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSymbolIdMatchesMetadata() { await TestSymbolIdMatchesMetadataAsync(LanguageNames.CSharp); await TestSymbolIdMatchesMetadataAsync(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotReusedOnAssemblyDiffers() { await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.CSharp); await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestThrowsOnGenerateNamespace() { var namespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol("Outerspace"); using var context = TestContext.Create(); await Assert.ThrowsAsync<ArgumentException>(async () => { await context.GenerateSourceAsync(namespaceSymbol); }); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseGenerateMemberOfGeneratedType() { var metadataSource = "public class C { public bool Is; }"; using var context = TestContext.Create(LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource)); var a = await context.GenerateSourceAsync("C"); var b = await context.GenerateSourceAsync("C.Is"); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseRepeatGeneration() { using var context = TestContext.Create(); var a = await context.GenerateSourceAsync(); var b = await context.GenerateSourceAsync(); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestWorkspaceContextHasReasonableProjectName() { using var context = TestContext.Create(); var compilation = await context.DefaultProject.GetCompilationAsync(); var result = await context.GenerateSourceAsync(compilation.ObjectType); var openedDocument = context.GetDocument(result); Assert.Equal("mscorlib", openedDocument.Project.AssemblyName); Assert.Equal("mscorlib", openedDocument.Project.Name); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseGenerateFromDifferentProject() { using var context = TestContext.Create(); var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.CSharp).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = await context.GenerateSourceAsync(project: context.DefaultProject); var b = await context.GenerateSourceAsync(project: project); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotReusedGeneratingForDifferentLanguage() { using var context = TestContext.Create(LanguageNames.CSharp); var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.VisualBasic).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = await context.GenerateSourceAsync(project: context.DefaultProject); var b = await context.GenerateSourceAsync(project: project); TestContext.VerifyDocumentNotReused(a, b); } [WorkItem(546311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546311")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task FormatMetadataAsSource() { using var context = TestContext.Create(LanguageNames.CSharp); var file = await context.GenerateSourceAsync("System.Console", project: context.DefaultProject); var document = context.GetDocument(file); await Formatter.FormatAsync(document); } [WorkItem(530829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task IndexedProperty() { var metadataSource = @" Public Class C Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|get_IndexProp|](int p1); public void set_IndexProp(int p1, string value); }}"; var symbolName = "C.get_IndexProp"; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(566688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566688")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task AttributeReferencingInternalNestedType() { var metadataSource = @"using System; [My(typeof(D))] public class C { public C() { } internal class D { } } public class MyAttribute : Attribute { public MyAttribute(Type t) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [My(typeof(D))] public class [|C|] {{ public C(); }}"; var symbolName = "C"; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(530978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530978")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestAttributesOnMembers(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"using System; [Obsolete] public class C { [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 { get; set; } [Obsolete] public int prop2 { get { return 10; } set {} } [Obsolete] public void method1() {} [Obsolete] public C() {} [Obsolete] ~C() {} [Obsolete] public int this[int x] { get { return 10; } set {} } [Obsolete] public event Action event1; [Obsolete] public event Action event2 { add {} remove {}} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} [Obsolete] public static C operator + (C c1, C c2) { return new C(); } } "; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public C(); [Obsolete] ~C(); [Obsolete] public int this[int x] {{ get; set; }} [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get; set; }} [Obsolete] public event Action event1; [Obsolete] public event Action event2; [Obsolete] public void method1(); public void method2([CallerMemberName] string name = """"); [Obsolete] public static C operator +(C c1, C c2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> <Obsolete> Public Class [|C|] <Obsolete> <ThreadStatic> Public field1 As Integer <Obsolete> Public Sub New() <Obsolete> Public Property prop1 As Integer <Obsolete> Public Property prop2 As Integer <Obsolete> Default Public Property Item(x As Integer) As Integer <Obsolete> Public Event event1 As Action <Obsolete> Public Event event2 As Action <Obsolete> Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") <Obsolete> Protected Overrides Sub Finalize() <Obsolete> Public Shared Operator +(c1 As C, c2 As C) As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get {{ return 10; }} set {{ }} }} [Obsolete] public int this[int x] {{ get {{ return 10; }} set {{ }} }} [Obsolete] public event Action event1; [Obsolete] public event Action event2 {{ add {{ }} remove {{ }} }} [Obsolete] public void method1() {{ }} [Obsolete] public C() {{ }} [Obsolete] ~C() {{ }} public void method2([CallerMemberName] string name = """") {{ }} [Obsolete] public static C operator +(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get {{ return 10; }} set {{ }} }} [Obsolete] public int this[int x] {{ get {{ return 10; }} set {{ }} }} [Obsolete] public event Action event1; [Obsolete] public event Action event2 {{ add {{ }} remove {{ }} }} [Obsolete] public void method1() {{ }} [Obsolete] public C() {{ }} [Obsolete] ~C() {{ }} public void method2([CallerMemberName] string name = """") {{ }} [Obsolete] public static C operator +(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(530923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530923")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEmptyLineBetweenMembers(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"using System; public class C { public int field1; public int prop1 { get; set; } public int field2; public int prop2 { get { return 10; } set {} } public void method1() {} public C() {} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} ~C() {} public int this[int x] { get { return 10; } set {} } public event Action event1; public static C operator + (C c1, C c2) { return new C(); } public event Action event2 { add {} remove {}} public static C operator - (C c1, C c2) { return new C(); } } "; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] public class [|C|] {{ public int field1; public int field2; public C(); ~C(); public int this[int x] {{ get; set; }} public int prop1 {{ get; set; }} public int prop2 {{ get; set; }} public event Action event1; public event Action event2; public void method1(); public void method2([CallerMemberName] string name = """"); public static C operator +(C c1, C c2); public static C operator -(C c1, C c2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> Public Class [|C|] Public field1 As Integer Public field2 As Integer Public Sub New() Public Property prop1 As Integer Public Property prop2 As Integer Default Public Property Item(x As Integer) As Integer Public Event event1 As Action Public Event event2 As Action Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") Protected Overrides Sub Finalize() Public Shared Operator +(c1 As C, c2 As C) As C Public Shared Operator -(c1 As C, c2 As C) As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; public class [|C|] {{ public int field1; public int field2; public int prop1 {{ get; set; }} public int prop2 {{ get {{ return 10; }} set {{ }} }} public int this[int x] {{ get {{ return 10; }} set {{ }} }} public event Action event1; public event Action event2 {{ add {{ }} remove {{ }} }} public void method1() {{ }} public void method2([CallerMemberName] string name = """") {{ }} ~C() {{ }} public static C operator +(C c1, C c2) {{ return new C(); }} public static C operator -(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; public class [|C|] {{ public int field1; public int field2; public int prop1 {{ get; set; }} public int prop2 {{ get {{ return 10; }} set {{ }} }} public int this[int x] {{ get {{ return 10; }} set {{ }} }} public event Action event1; public event Action event2 {{ add {{ }} remove {{ }} }} public void method1() {{ }} public void method2([CallerMemberName] string name = """") {{ }} ~C() {{ }} public static C operator +(C c1, C c2) {{ return new C(); }} public static C operator -(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(728644, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728644")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEmptyLineBetweenMembers2(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; /// <summary>T:IGoo</summary> public interface IGoo { /// <summary>P:IGoo.Prop1</summary> Uri Prop1 { get; set; } /// <summary>M:IGoo.Method1</summary> Uri Method1(); } "; var symbolName = "IGoo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; // // {FeaturesResources.Summary_colon} // T:IGoo public interface [|IGoo|] {{ // // {FeaturesResources.Summary_colon} // P:IGoo.Prop1 Uri Prop1 {{ get; set; }} // // {FeaturesResources.Summary_colon} // M:IGoo.Method1 Uri Method1(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System ' ' {FeaturesResources.Summary_colon} ' T:IGoo Public Interface [|IGoo|] ' ' {FeaturesResources.Summary_colon} ' P:IGoo.Prop1 Property Prop1 As Uri ' ' {FeaturesResources.Summary_colon} ' M:IGoo.Method1 Function Method1() As Uri End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, includeXmlDocComments: true); } [WorkItem(679114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679114"), WorkItem(715013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDefaultValueEnum(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System.IO; public class Test { public void goo(FileOptions options = 0) {} } "; var symbolName = "Test"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.IO; public class [|Test|] {{ public Test(); public void goo(FileOptions options = FileOptions.None); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.IO Public Class [|Test|] Public Sub New() Public Sub goo(Optional options As FileOptions = FileOptions.None) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.IO; public class [|Test|] {{ public void goo(FileOptions options = FileOptions.None) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.IO; public class [|Test|] {{ public void goo(FileOptions options = FileOptions.None) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(651261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651261")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullAttribute(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; [Test(null)] public class TestAttribute : Attribute { public TestAttribute(int[] i) { } }"; var symbolName = "TestAttribute"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <Test(Nothing)> Public Class [|TestAttribute|] Inherits Attribute Public Sub New(i() As Integer) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNavigationViaReducedExtensionMethodCS() { var metadata = @"using System; public static class ObjectExtensions { public static void M(this object o, int x) { } }"; var sourceWithSymbolReference = @" class C { void M() { new object().[|M|](5); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public static class ObjectExtensions {{ public static void [|M|](this object o, int x); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNavigationViaReducedExtensionMethodVB() { var metadata = @"Imports System.Runtime.CompilerServices Namespace NS Public Module StringExtensions <Extension()> Public Sub M(ByVal o As String, x As Integer) End Sub End Module End Namespace"; var sourceWithSymbolReference = @" Imports NS.StringExtensions Public Module C Sub M() Dim s = ""Yay"" s.[|M|](1) End Sub End Module"; var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Runtime.CompilerServices Namespace NS <Extension> Public Module StringExtensions <Extension> Public Sub [|M|](o As String, x As Integer) End Module End Namespace"; using var context = TestContext.Create( LanguageNames.VisualBasic, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestIndexersAndOperators(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"public class Program { public int this[int x] { get { return 0; } set { } } public static Program operator + (Program p1, Program p2) { return new Program(); } }"; var symbolName = "Program"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public class [|Program|] {{ public Program(); public int this[int x] {{ get; set; }} public static Program operator +(Program p1, Program p2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Class [|Program|] Public Sub New() Default Public Property Item(x As Integer) As Integer Public Shared Operator +(p1 As Program, p2 As Program) As Program End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|Program|] {{ public int this[int x] {{ get {{ return 0; }} set {{ }} }} public static Program operator +(Program p1, Program p2) {{ return new Program(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|Program|] {{ public int this[int x] {{ get {{ return 0; }} set {{ }} }} public static Program operator +(Program p1, Program p2) {{ return new Program(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestComImport1(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface IComImport { void MOverload(); void X(); void MOverload(int i); int Prop { get; } }"; var symbolName = "IComImport"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.InteropServices; [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ void MOverload(); void X(); void MOverload(int i); int Prop {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Runtime.InteropServices <Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")> Public Interface [|IComImport|] ReadOnly Property Prop As Integer Sub MOverload() Sub X() Sub MOverload(i As Integer) End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ int Prop {{ get; }} void MOverload(); void X(); void MOverload(int i); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ int Prop {{ get; }} void MOverload(); void X(); void MOverload(int i); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestOptionalParameterWithDefaultLiteral(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System.Threading; public class C { public void M(CancellationToken cancellationToken = default(CancellationToken)) { } }"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Threading; public class [|C|] {{ public C(); public void M(CancellationToken cancellationToken = default); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Threading Public Class [|C|] Public Sub New() Public Sub M(Optional cancellationToken As CancellationToken = Nothing) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Threading; public class [|C|] {{ public void M(CancellationToken cancellationToken = default(CancellationToken)) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Threading; public class [|C|] {{ public void M(CancellationToken cancellationToken = default(CancellationToken)) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; var languageVersion = language switch { OriginatingProjectLanguage.CSharp => "7.1", OriginatingProjectLanguage.VisualBasic => "15.5", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, languageVersion: languageVersion); } [WorkItem(446567, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=446567")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDocCommentsWithUnixNewLine(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; /// <summary>T:IGoo" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> public interface IGoo { /// <summary>P:IGoo.Prop1" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> Uri Prop1 { get; set; } /// <summary>M:IGoo.Method1" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> Uri Method1(); } "; var symbolName = "IGoo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; // // {FeaturesResources.Summary_colon} // T:IGoo ABCDE FGHIJK public interface [|IGoo|] {{ // // {FeaturesResources.Summary_colon} // P:IGoo.Prop1 ABCDE FGHIJK Uri Prop1 {{ get; set; }} // // {FeaturesResources.Summary_colon} // M:IGoo.Method1 ABCDE FGHIJK Uri Method1(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System ' ' {FeaturesResources.Summary_colon} ' T:IGoo ABCDE FGHIJK Public Interface [|IGoo|] ' ' {FeaturesResources.Summary_colon} ' P:IGoo.Prop1 ABCDE FGHIJK Property Prop1 As Uri ' ' {FeaturesResources.Summary_colon} ' M:IGoo.Method1 ABCDE FGHIJK Function Method1() As Uri End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, includeXmlDocComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Type() { var metadata = @"using System; public class TestType<T> where T : unmanaged { }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new [|TestType|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|TestType|]<T> where T : unmanaged {{ public TestType(); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Method() { var metadata = @"using System; public class TestType { public void M<T>() where T : unmanaged { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M|]<T>() where T : unmanaged; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Delegate() { var metadata = @"using System; public delegate void D<T>() where T : unmanaged;"; var sourceWithSymbolReference = @" class C { void M([|D|]&lt;int&gt; lambda) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public delegate void [|D|]<T>() where T : unmanaged;"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSByteMinValue() { var source = @" class C { sbyte Goo = sbyte.[|MinValue|]; }"; var expected = "public const SByte MinValue = -128;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSByteMinValueVB() { var source = @" Class C Public Goo = SByte.[|MinValue|] End Class"; var expected = "Public Const MinValue As [SByte] = -128"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt16MinValue() { var source = @" class C { short Goo = short.[|MinValue|]; }"; var expected = $"public const Int16 MinValue = -32768;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt16MinValueVB() { var source = @" Class C Public Goo = Short.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int16 = -32768"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt32MinValue() { var source = @" class C { int Goo = int.[|MinValue|]; }"; var expected = $"public const Int32 MinValue = -2147483648;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt32MinValueVB() { var source = @" Class C Public Goo = Integer.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int32 = -2147483648"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt64MinValue() { var source = @" class C { long Goo = long.[|MinValue|]; }"; var expected = $"public const Int64 MinValue = -9223372036854775808;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt64MinValueVB() { var source = @" Class C Public Goo = Long.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int64 = -9223372036854775808"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStruct_ReadOnlyField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public readonly int i; } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct [|S|] {{ public readonly int i; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure [|S|] Public ReadOnly i As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStruct_ReadOnlyField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int i; } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct [|S|] {{ public readonly int i; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure [|S|] Public ReadOnly i As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestRefStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public ref struct S { } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public ref struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsByRefLikeAttribute> <Obsolete(""Types with embedded references are not supported in this version of your compiler."", True)> Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyRefStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly ref struct S { } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly ref struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsByRefLikeAttribute> <IsReadOnlyAttribute> <Obsolete(""Types with embedded references are not supported in this version of your compiler."", True)> Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyMethod(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly void M() {} } "; var symbolName = "S.M"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly void [|M|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S <IsReadOnlyAttribute> Public Sub [|M|]() End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyMethod_InReadOnlyStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public void M() {} } "; var symbolName = "S.M"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct S {{ public void [|M|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure S Public Sub [|M|]() End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnly(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnly_CSharp7_3(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; var metadataLanguageVersion = language switch { OriginatingProjectLanguage.CSharp => "7.3", OriginatingProjectLanguage.VisualBasic => "Preview", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, metadataLanguageVersion: metadataLanguageVersion); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public readonly int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct S {{ public int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { readonly get => 123; set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ readonly get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ readonly get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ readonly get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_Get_ReadOnlySet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get => 123; readonly set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ get; readonly set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ get {{ return 123; }} readonly set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ get {{ return 123; }} readonly set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet_ReadOnlySet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int P { get => 123; set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|P|] {{ get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|P|] {{ get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructIndexer_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int this[int i] => i; } "; var symbolName = "S.Item"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public struct S {{ public readonly int [|this|][int i] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Structure S Default Public ReadOnly Property [|Item|](i As Integer) As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|this|][int i] => i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|this|][int i] => i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructIndexer_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int this[int i] { readonly get => i; set {} } } "; var symbolName = "S.Item"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public struct S {{ public int [|this|][int i] {{ readonly get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Structure S Default Public Property [|Item|](i As Integer) As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|this|][int i] {{ readonly get {{ return i; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|this|][int i] {{ readonly get {{ return i; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly event System.Action E { add {} remove {} } } "; var symbolName = "S.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public struct S {{ public readonly event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Public Structure S Public Event [|E|] As Action End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public event System.Action E { add {} remove {} } } "; var symbolName = "S.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public readonly struct S {{ public event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsReadOnlyAttribute> Public Structure S Public Event [|E|] As Action End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Type() { var metadata = @"using System; public class TestType<T> where T : notnull { }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new [|TestType|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|TestType|]<T> where T : notnull {{ public TestType(); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Method() { var metadata = @"using System; public class TestType { public void M<T>() where T : notnull { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M|]<T>() where T : notnull; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Delegate() { var metadata = @"using System; public delegate void D<T>() where T : notnull;"; var sourceWithSymbolReference = @" class C { void M([|D|]&lt;int&gt; lambda) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public delegate void [|D|]<T>() where T : notnull;"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable1() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); #nullable enable }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable2() { var metadata = @" using System; public class TestType { public void M1(string s) { } #nullable enable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); #nullable disable public void [|M1|](string s); #nullable enable public void M2(string s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable3() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } public void M3(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); public void M3(string s); #nullable enable }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable4() { var metadata = @" #nullable enable using System; public class TestType { public void M1(ICloneable s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable using System; public class TestType {{ public TestType(); public void [|M1|](ICloneable s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable5() { var metadata = @" #nullable enable using System; public class TestType { public void M1(ICloneable s) { #nullable disable } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable using System; public class TestType {{ public TestType(); public void [|M1|](ICloneable s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable6() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T? s) where T : class { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|]<T>(T? s) where T : class; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable7() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) where T : class { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|]<T>(T s) where T : class; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable8() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T? s) where T : struct { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|]((int?)0); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T? s) where T : struct; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable9() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) where T : struct { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](0); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s) where T : struct; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable10() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable11() { var metadata = @" using System; public class TestType { public void M1<T>(T s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable12() { var metadata = @" #nullable enable using System; namespace N { public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new N.TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable namespace N {{ public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); #nullable enable }} }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable13() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public class Nested { public void NestedM(string s) { } } #nullable enable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); public void M2(string s); public class Nested {{ public Nested(); #nullable disable public void NestedM(string s); #nullable enable }} }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDynamic1() { var metadata = @" using System; public class TestType { public void M1(dynamic s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|](dynamic s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(22431, "https://github.com/dotnet/roslyn/issues/22431")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestCDATAComment() { var source = @" public enum BinaryOperatorKind { /// <summary> /// Represents the <![CDATA['<<']]> operator. /// </summary> LeftShift = 0x8, } "; var symbolName = "BinaryOperatorKind.LeftShift"; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum BinaryOperatorKind {{ // // {FeaturesResources.Summary_colon} // Represents the '<<' operator. [|LeftShift|] = 8 }}"; await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS, includeXmlDocComments: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.CSharp; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests : AbstractMetadataAsSourceTests { public enum OriginatingProjectLanguage { CSharp, VisualBasic, } private static string ToLanguageName(OriginatingProjectLanguage language) => language switch { OriginatingProjectLanguage.CSharp => LanguageNames.CSharp, OriginatingProjectLanguage.VisualBasic => LanguageNames.VisualBasic, _ => throw ExceptionUtilities.UnexpectedValue(language), }; [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestClass(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546241")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInterface(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public interface I {}"; var symbolName = "I"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public interface [|I|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Interface [|I|] End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|I|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|I|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestConstructor(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C {}"; var symbolName = "C..ctor"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public [|C|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub [|New|]() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestMethod(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public void Goo() {} }"; var symbolName = "C.Goo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public void [|Goo|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Sub [|Goo|]() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public void [|Goo|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public void [|Goo|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public string S; }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public string [|S|]; public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public [|S|] As String Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546240")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestProperty(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public string S { get; protected set; } }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|S|] {{ get; protected set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Property [|S|] As String End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|] {{ get; protected set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public string [|S|] {{ get; protected set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546194")] [WorkItem(546291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546291")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "using System; public class C { public event Action E; }"; var symbolName = "C.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public class C {{ public C(); public event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Public Class C Public Sub New() Public Event [|E|] As Action End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public class C {{ public event Action [|E|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public class C {{ public event Action [|E|]; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNestedType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { protected class D { } }"; var symbolName = "C+D"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); protected class [|D|] {{ public D(); }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Protected Class [|D|] Public Sub New() End Class End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ protected class [|D|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ protected class [|D|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnum(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E { A, B, C }"; var symbolName = "E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum [|E|] {{ A = 0, B = 1, C = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum [|E|] A = 0 B = 1 C = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum [|E|] {{ A, B, C }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum [|E|] {{ A, B, C }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumFromField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E { A, B, C }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E {{ A = 0, B = 1, [|C|] = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E A = 0 B = 1 [|C|] = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546273")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithUnderlyingType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A = 0, B = 1, [|C|] = 2 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A = 0 B = 1 [|C|] = 2 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(650741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650741")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithOverflowingUnderlyingType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : ulong { A = 9223372036854775808 }"; var symbolName = "E.A"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : ulong {{ [|A|] = 9223372036854775808 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As ULong [|A|] = 9223372036854775808UL End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : ulong {{ [|A|] = 9223372036854775808uL }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : ulong {{ [|A|] = 9223372036854775808uL }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEnumWithDifferentValues(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }"; var symbolName = "E.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A = 1, B = 2, [|C|] = 3 }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A = 1 B = 2 [|C|] = 3 End Enum", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A = 1, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public enum E : short {{ A = 1, B, [|C|] }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInNamespace(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "namespace N { public class C {} }"; var symbolName = "N.C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Namespace N Public Class [|C|] Public Sub New() End Class End Namespace", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion namespace N {{ public class [|C|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion namespace N {{ public class [|C|] {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace1() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N; public class [|C|] {{ public C(); }}"); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace2() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "9"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}"); } [WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTypeInFileScopedNamespace3() { var metadataSource = "namespace N { public class C {} }"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource), languageVersion: "10"); context.Workspace.SetOptions(context.Workspace.Options.WithChangedOption( CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent))); await context.GenerateAndVerifySourceAsync("N.C", $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}"); } [WorkItem(546223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546223")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInlineConstant(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"public class C { public const string S = ""Hello mas""; }"; var symbolName = "C.S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public const string [|S|] = ""Hello mas""; public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Const [|S|] As String = ""Hello mas"" Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public const string [|S|] = ""Hello mas""; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public const string [|S|] = ""Hello mas""; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546221")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInlineTypeOf(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System; public class MyTypeAttribute : Attribute { public MyTypeAttribute(Type type) {} } [MyType(typeof(string))] public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [MyType(typeof(string))] public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <MyType(GetType(String))> Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion [MyType(typeof(string))] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion [MyType(typeof(string))] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546231")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNoDefaultConstructorInStructs(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public struct S {}"; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReferenceDefinedType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public static C Create() { return new C(); } }"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public static C Create(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() Public Shared Function Create() As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public static C Create() {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public static C Create() {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestGenericType(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class G<SomeType> { public SomeType S; }"; var symbolName = "G`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|G|]<SomeType> {{ public SomeType S; public G(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|G|](Of SomeType) Public S As SomeType Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|G|]<SomeType> {{ public SomeType S; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|G|]<SomeType> {{ public SomeType S; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(38916, "https://github.com/dotnet/roslyn/issues/38916")] public async Task TestParameterAttributes(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public class C<[My] T> { public void Method([My] T x, [My] T y) { } } internal class MyAttribute : System.Attribute { } "; var symbolName = "C`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|]<[MyAttribute] T> {{ public C(); public void Method([MyAttribute] T x, [MyAttribute] T y); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|](Of T) Public Sub New() Public Sub Method(<MyAttribute> x As T, <MyAttribute> y As T) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|]<[My] T> {{ public void Method([My] T x, [My] T y) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|]<[My] T> {{ public void Method([My] T x, [My] T y) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(38916, "https://github.com/dotnet/roslyn/issues/38916")] public async Task TestGenericWithNullableReferenceTypes(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" #nullable enable public interface C<T> { bool Equals([AllowNull] T other); } internal class AllowNullAttribute : System.Attribute { } "; var symbolName = "C`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public interface [|C|]<T> {{ bool Equals([AllowNullAttribute] T other); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <NullableContextAttribute(1)> Public Interface [|C|](Of T) Function Equals(<AllowNullAttribute> other As T) As Boolean End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|C|]<T> {{ bool Equals([AllowNull] T other); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public interface [|C|]<T> {{ bool Equals([AllowNull] T other); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestGenericDelegate(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = "public class C { public delegate void D<SomeType>(SomeType s); }"; var symbolName = "C+D`1"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public delegate void [|D|]<SomeType>(SomeType s); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Delegate Sub [|D|](Of SomeType)(s As SomeType) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public delegate void [|D|]<SomeType>(SomeType s); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class C {{ public delegate void [|D|]<SomeType>(SomeType s); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(546200, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546200")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestAttribute(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System; namespace N { public class WorkingAttribute : Attribute { public WorkingAttribute(bool working) {} } } [N.Working(true)] public class C {}"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using N; [Working(true)] public class [|C|] {{ public C(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports N <Working(True)> Public Class [|C|] Public Sub New() End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using N; [Working(true)] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using N; [Working(true)] public class [|C|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSymbolIdMatchesMetadata() { await TestSymbolIdMatchesMetadataAsync(LanguageNames.CSharp); await TestSymbolIdMatchesMetadataAsync(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotReusedOnAssemblyDiffers() { await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.CSharp); await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestThrowsOnGenerateNamespace() { var namespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol("Outerspace"); using var context = TestContext.Create(); await Assert.ThrowsAsync<ArgumentException>(async () => { await context.GenerateSourceAsync(namespaceSymbol); }); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseGenerateMemberOfGeneratedType() { var metadataSource = "public class C { public bool Is; }"; using var context = TestContext.Create(LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource)); var a = await context.GenerateSourceAsync("C"); var b = await context.GenerateSourceAsync("C.Is"); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseRepeatGeneration() { using var context = TestContext.Create(); var a = await context.GenerateSourceAsync(); var b = await context.GenerateSourceAsync(); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestWorkspaceContextHasReasonableProjectName() { using var context = TestContext.Create(); var compilation = await context.DefaultProject.GetCompilationAsync(); var result = await context.GenerateSourceAsync(compilation.ObjectType); var openedDocument = context.GetDocument(result); Assert.Equal("mscorlib", openedDocument.Project.AssemblyName); Assert.Equal("mscorlib", openedDocument.Project.Name); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReuseGenerateFromDifferentProject() { using var context = TestContext.Create(); var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.CSharp).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = await context.GenerateSourceAsync(project: context.DefaultProject); var b = await context.GenerateSourceAsync(project: project); TestContext.VerifyDocumentReused(a, b); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotReusedGeneratingForDifferentLanguage() { using var context = TestContext.Create(LanguageNames.CSharp); var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.VisualBasic).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = await context.GenerateSourceAsync(project: context.DefaultProject); var b = await context.GenerateSourceAsync(project: project); TestContext.VerifyDocumentNotReused(a, b); } [WorkItem(546311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546311")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task FormatMetadataAsSource() { using var context = TestContext.Create(LanguageNames.CSharp); var file = await context.GenerateSourceAsync("System.Console", project: context.DefaultProject); var document = context.GetDocument(file); await Formatter.FormatAsync(document); } [WorkItem(530829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task IndexedProperty() { var metadataSource = @" Public Class C Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|get_IndexProp|](int p1); public void set_IndexProp(int p1, string value); }}"; var symbolName = "C.get_IndexProp"; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(566688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566688")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task AttributeReferencingInternalNestedType() { var metadataSource = @"using System; [My(typeof(D))] public class C { public C() { } internal class D { } } public class MyAttribute : Attribute { public MyAttribute(Type t) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [My(typeof(D))] public class [|C|] {{ public C(); }}"; var symbolName = "C"; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(530978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530978")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestAttributesOnMembers(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"using System; [Obsolete] public class C { [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 { get; set; } [Obsolete] public int prop2 { get { return 10; } set {} } [Obsolete] public void method1() {} [Obsolete] public C() {} [Obsolete] ~C() {} [Obsolete] public int this[int x] { get { return 10; } set {} } [Obsolete] public event Action event1; [Obsolete] public event Action event2 { add {} remove {}} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} [Obsolete] public static C operator + (C c1, C c2) { return new C(); } } "; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public C(); [Obsolete] ~C(); [Obsolete] public int this[int x] {{ get; set; }} [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get; set; }} [Obsolete] public event Action event1; [Obsolete] public event Action event2; [Obsolete] public void method1(); public void method2([CallerMemberName] string name = """"); [Obsolete] public static C operator +(C c1, C c2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> <Obsolete> Public Class [|C|] <Obsolete> <ThreadStatic> Public field1 As Integer <Obsolete> Public Sub New() <Obsolete> Public Property prop1 As Integer <Obsolete> Public Property prop2 As Integer <Obsolete> Default Public Property Item(x As Integer) As Integer <Obsolete> Public Event event1 As Action <Obsolete> Public Event event2 As Action <Obsolete> Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") <Obsolete> Protected Overrides Sub Finalize() <Obsolete> Public Shared Operator +(c1 As C, c2 As C) As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get {{ return 10; }} set {{ }} }} [Obsolete] public int this[int x] {{ get {{ return 10; }} set {{ }} }} [Obsolete] public event Action event1; [Obsolete] public event Action event2 {{ add {{ }} remove {{ }} }} [Obsolete] public void method1() {{ }} [Obsolete] public C() {{ }} [Obsolete] ~C() {{ }} public void method2([CallerMemberName] string name = """") {{ }} [Obsolete] public static C operator +(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get {{ return 10; }} set {{ }} }} [Obsolete] public int this[int x] {{ get {{ return 10; }} set {{ }} }} [Obsolete] public event Action event1; [Obsolete] public event Action event2 {{ add {{ }} remove {{ }} }} [Obsolete] public void method1() {{ }} [Obsolete] public C() {{ }} [Obsolete] ~C() {{ }} public void method2([CallerMemberName] string name = """") {{ }} [Obsolete] public static C operator +(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(530923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530923")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEmptyLineBetweenMembers(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"using System; public class C { public int field1; public int prop1 { get; set; } public int field2; public int prop2 { get { return 10; } set {} } public void method1() {} public C() {} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} ~C() {} public int this[int x] { get { return 10; } set {} } public event Action event1; public static C operator + (C c1, C c2) { return new C(); } public event Action event2 { add {} remove {}} public static C operator - (C c1, C c2) { return new C(); } } "; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] public class [|C|] {{ public int field1; public int field2; public C(); ~C(); public int this[int x] {{ get; set; }} public int prop1 {{ get; set; }} public int prop2 {{ get; set; }} public event Action event1; public event Action event2; public void method1(); public void method2([CallerMemberName] string name = """"); public static C operator +(C c1, C c2); public static C operator -(C c1, C c2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> Public Class [|C|] Public field1 As Integer Public field2 As Integer Public Sub New() Public Property prop1 As Integer Public Property prop2 As Integer Default Public Property Item(x As Integer) As Integer Public Event event1 As Action Public Event event2 As Action Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") Protected Overrides Sub Finalize() Public Shared Operator +(c1 As C, c2 As C) As C Public Shared Operator -(c1 As C, c2 As C) As C End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; public class [|C|] {{ public int field1; public int field2; public int prop1 {{ get; set; }} public int prop2 {{ get {{ return 10; }} set {{ }} }} public int this[int x] {{ get {{ return 10; }} set {{ }} }} public event Action event1; public event Action event2 {{ add {{ }} remove {{ }} }} public void method1() {{ }} public void method2([CallerMemberName] string name = """") {{ }} ~C() {{ }} public static C operator +(C c1, C c2) {{ return new C(); }} public static C operator -(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.CompilerServices; public class [|C|] {{ public int field1; public int field2; public int prop1 {{ get; set; }} public int prop2 {{ get {{ return 10; }} set {{ }} }} public int this[int x] {{ get {{ return 10; }} set {{ }} }} public event Action event1; public event Action event2 {{ add {{ }} remove {{ }} }} public void method1() {{ }} public void method2([CallerMemberName] string name = """") {{ }} ~C() {{ }} public static C operator +(C c1, C c2) {{ return new C(); }} public static C operator -(C c1, C c2) {{ return new C(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(728644, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728644")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestEmptyLineBetweenMembers2(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; /// <summary>T:IGoo</summary> public interface IGoo { /// <summary>P:IGoo.Prop1</summary> Uri Prop1 { get; set; } /// <summary>M:IGoo.Method1</summary> Uri Method1(); } "; var symbolName = "IGoo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; // // {FeaturesResources.Summary_colon} // T:IGoo public interface [|IGoo|] {{ // // {FeaturesResources.Summary_colon} // P:IGoo.Prop1 Uri Prop1 {{ get; set; }} // // {FeaturesResources.Summary_colon} // M:IGoo.Method1 Uri Method1(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System ' ' {FeaturesResources.Summary_colon} ' T:IGoo Public Interface [|IGoo|] ' ' {FeaturesResources.Summary_colon} ' P:IGoo.Prop1 Property Prop1 As Uri ' ' {FeaturesResources.Summary_colon} ' M:IGoo.Method1 Function Method1() As Uri End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, includeXmlDocComments: true); } [WorkItem(679114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679114"), WorkItem(715013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDefaultValueEnum(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System.IO; public class Test { public void goo(FileOptions options = 0) {} } "; var symbolName = "Test"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.IO; public class [|Test|] {{ public Test(); public void goo(FileOptions options = FileOptions.None); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.IO Public Class [|Test|] Public Sub New() Public Sub goo(Optional options As FileOptions = FileOptions.None) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.IO; public class [|Test|] {{ public void goo(FileOptions options = FileOptions.None) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.IO; public class [|Test|] {{ public void goo(FileOptions options = FileOptions.None) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(651261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651261")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullAttribute(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; [Test(null)] public class TestAttribute : Attribute { public TestAttribute(int[] i) { } }"; var symbolName = "TestAttribute"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <Test(Nothing)> Public Class [|TestAttribute|] Inherits Attribute Public Sub New(i() As Integer) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNavigationViaReducedExtensionMethodCS() { var metadata = @"using System; public static class ObjectExtensions { public static void M(this object o, int x) { } }"; var sourceWithSymbolReference = @" class C { void M() { new object().[|M|](5); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public static class ObjectExtensions {{ public static void [|M|](this object o, int x); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNavigationViaReducedExtensionMethodVB() { var metadata = @"Imports System.Runtime.CompilerServices Namespace NS Public Module StringExtensions <Extension()> Public Sub M(ByVal o As String, x As Integer) End Sub End Module End Namespace"; var sourceWithSymbolReference = @" Imports NS.StringExtensions Public Module C Sub M() Dim s = ""Yay"" s.[|M|](1) End Sub End Module"; var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Runtime.CompilerServices Namespace NS <Extension> Public Module StringExtensions <Extension> Public Sub [|M|](o As String, x As Integer) End Module End Namespace"; using var context = TestContext.Create( LanguageNames.VisualBasic, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestIndexersAndOperators(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @"public class Program { public int this[int x] { get { return 0; } set { } } public static Program operator + (Program p1, Program p2) { return new Program(); } }"; var symbolName = "Program"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public class [|Program|] {{ public Program(); public int this[int x] {{ get; set; }} public static Program operator +(Program p1, Program p2); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Class [|Program|] Public Sub New() Default Public Property Item(x As Integer) As Integer Public Shared Operator +(p1 As Program, p2 As Program) As Program End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|Program|] {{ public int this[int x] {{ get {{ return 0; }} set {{ }} }} public static Program operator +(Program p1, Program p2) {{ return new Program(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|Program|] {{ public int this[int x] {{ get {{ return 0; }} set {{ }} }} public static Program operator +(Program p1, Program p2) {{ return new Program(); }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestComImport1(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface IComImport { void MOverload(); void X(); void MOverload(int i); int Prop { get; } }"; var symbolName = "IComImport"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.InteropServices; [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ void MOverload(); void X(); void MOverload(int i); int Prop {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Runtime.InteropServices <Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")> Public Interface [|IComImport|] ReadOnly Property Prop As Integer Sub MOverload() Sub X() Sub MOverload(i As Integer) End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ int Prop {{ get; }} void MOverload(); void X(); void MOverload(int i); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [ComImport] [Guid(""666A175D-2448-447A-B786-CCC82CBEF156"")] public interface [|IComImport|] {{ int Prop {{ get; }} void MOverload(); void X(); void MOverload(int i); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestOptionalParameterWithDefaultLiteral(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" using System.Threading; public class C { public void M(CancellationToken cancellationToken = default(CancellationToken)) { } }"; var symbolName = "C"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Threading; public class [|C|] {{ public C(); public void M(CancellationToken cancellationToken = default); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Threading Public Class [|C|] Public Sub New() Public Sub M(Optional cancellationToken As CancellationToken = Nothing) End Class", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Threading; public class [|C|] {{ public void M(CancellationToken cancellationToken = default(CancellationToken)) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Threading; public class [|C|] {{ public void M(CancellationToken cancellationToken = default(CancellationToken)) {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; var languageVersion = language switch { OriginatingProjectLanguage.CSharp => "7.1", OriginatingProjectLanguage.VisualBasic => "15.5", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, languageVersion: languageVersion); } [WorkItem(446567, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=446567")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDocCommentsWithUnixNewLine(OriginatingProjectLanguage language, bool allowDecompilation) { var source = @" using System; /// <summary>T:IGoo" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> public interface IGoo { /// <summary>P:IGoo.Prop1" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> Uri Prop1 { get; set; } /// <summary>M:IGoo.Method1" + "\n/// ABCDE\n" + @"/// FGHIJK</summary> Uri Method1(); } "; var symbolName = "IGoo"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; // // {FeaturesResources.Summary_colon} // T:IGoo ABCDE FGHIJK public interface [|IGoo|] {{ // // {FeaturesResources.Summary_colon} // P:IGoo.Prop1 ABCDE FGHIJK Uri Prop1 {{ get; set; }} // // {FeaturesResources.Summary_colon} // M:IGoo.Method1 ABCDE FGHIJK Uri Method1(); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System ' ' {FeaturesResources.Summary_colon} ' T:IGoo ABCDE FGHIJK Public Interface [|IGoo|] ' ' {FeaturesResources.Summary_colon} ' P:IGoo.Prop1 ABCDE FGHIJK Property Prop1 As Uri ' ' {FeaturesResources.Summary_colon} ' M:IGoo.Method1 ABCDE FGHIJK Function Method1() As Uri End Interface", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; public interface [|IGoo|] {{ Uri Prop1 {{ get; set; }} Uri Method1(); }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(source, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, includeXmlDocComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Type() { var metadata = @"using System; public class TestType<T> where T : unmanaged { }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new [|TestType|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|TestType|]<T> where T : unmanaged {{ public TestType(); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Method() { var metadata = @"using System; public class TestType { public void M<T>() where T : unmanaged { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M|]<T>() where T : unmanaged; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestUnmanagedCSharpConstraint_Delegate() { var metadata = @"using System; public delegate void D<T>() where T : unmanaged;"; var sourceWithSymbolReference = @" class C { void M([|D|]&lt;int&gt; lambda) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public delegate void [|D|]<T>() where T : unmanaged;"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "7.3", sourceWithSymbolReference: sourceWithSymbolReference); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSByteMinValue() { var source = @" class C { sbyte Goo = sbyte.[|MinValue|]; }"; var expected = "public const SByte MinValue = -128;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestSByteMinValueVB() { var source = @" Class C Public Goo = SByte.[|MinValue|] End Class"; var expected = "Public Const MinValue As [SByte] = -128"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt16MinValue() { var source = @" class C { short Goo = short.[|MinValue|]; }"; var expected = $"public const Int16 MinValue = -32768;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt16MinValueVB() { var source = @" Class C Public Goo = Short.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int16 = -32768"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt32MinValue() { var source = @" class C { int Goo = int.[|MinValue|]; }"; var expected = $"public const Int32 MinValue = -2147483648;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt32MinValueVB() { var source = @" Class C Public Goo = Integer.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int32 = -2147483648"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt64MinValue() { var source = @" class C { long Goo = long.[|MinValue|]; }"; var expected = $"public const Int64 MinValue = -9223372036854775808;"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.CSharp, expected); } [WorkItem(29786, "https://github.com/dotnet/roslyn/issues/29786")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInt64MinValueVB() { var source = @" Class C Public Goo = Long.[|MinValue|] End Class"; var expected = $"Public Const MinValue As Int64 = -9223372036854775808"; await GenerateAndVerifySourceLineAsync(source, LanguageNames.VisualBasic, expected); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStruct_ReadOnlyField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public readonly int i; } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct [|S|] {{ public readonly int i; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure [|S|] Public ReadOnly i As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStruct_ReadOnlyField(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int i; } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct [|S|] {{ public readonly int i; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure [|S|] Public ReadOnly i As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct [|S|] {{ public readonly int i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestRefStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public ref struct S { } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public ref struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsByRefLikeAttribute> <Obsolete(""Types with embedded references are not supported in this version of your compiler."", True)> Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyRefStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly ref struct S { } "; var symbolName = "S"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly ref struct [|S|] {{ }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsByRefLikeAttribute> <IsReadOnlyAttribute> <Obsolete(""Types with embedded references are not supported in this version of your compiler."", True)> Public Structure [|S|] End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly ref struct [|S|] {{ }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyMethod(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly void M() {} } "; var symbolName = "S.M"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly void [|M|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S <IsReadOnlyAttribute> Public Sub [|M|]() End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyMethod_InReadOnlyStruct(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public void M() {} } "; var symbolName = "S.M"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct S {{ public void [|M|](); }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure S Public Sub [|M|]() End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public void [|M|]() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnly(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnly_CSharp7_3(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; var metadataLanguageVersion = language switch { OriginatingProjectLanguage.CSharp => "7.3", OriginatingProjectLanguage.VisualBasic => "Preview", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation, metadataLanguageVersion: metadataLanguageVersion); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStructProperty_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public readonly int P { get; } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public readonly struct S {{ public int [|P|] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <IsReadOnlyAttribute> Public Structure S Public ReadOnly Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public readonly struct S {{ public int [|P|] {{ get; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { readonly get => 123; set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ readonly get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ readonly get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ readonly get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_Get_ReadOnlySet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int P { get => 123; readonly set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public int [|P|] {{ get; readonly set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ get {{ return 123; }} readonly set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|P|] {{ get {{ return 123; }} readonly set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructProperty_ReadOnlyGet_ReadOnlySet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int P { get => 123; set {} } } "; var symbolName = "S.P"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct S {{ public readonly int [|P|] {{ get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure S Public Property [|P|] As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|P|] {{ get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|P|] {{ get {{ return 123; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructIndexer_ReadOnlyGet(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly int this[int i] => i; } "; var symbolName = "S.Item"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public struct S {{ public readonly int [|this|][int i] {{ get; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Structure S Default Public ReadOnly Property [|Item|](i As Integer) As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|this|][int i] => i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly int [|this|][int i] => i; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStructIndexer_ReadOnlyGet_Set(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public int this[int i] { readonly get => i; set {} } } "; var symbolName = "S.Item"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public struct S {{ public int [|this|][int i] {{ readonly get; set; }} }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Structure S Default Public Property [|Item|](i As Integer) As Integer End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|this|][int i] {{ readonly get {{ return i; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public int [|this|][int i] {{ readonly get {{ return i; }} set {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public struct S { public readonly event System.Action E { add {} remove {} } } "; var symbolName = "S.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public struct S {{ public readonly event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Public Structure S Public Event [|E|] As Action End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public struct S {{ public readonly event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [WorkItem(34650, "https://github.com/dotnet/roslyn/issues/34650")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestReadOnlyStruct_ReadOnlyEvent(OriginatingProjectLanguage language, bool allowDecompilation) { var metadataSource = @" public readonly struct S { public event System.Action E { add {} remove {} } } "; var symbolName = "S.E"; var expected = (language, allowDecompilation) switch { (OriginatingProjectLanguage.CSharp, false) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public readonly struct S {{ public event Action [|E|]; }}", (OriginatingProjectLanguage.VisualBasic, false) => $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <IsReadOnlyAttribute> Public Structure S Public Event [|E|] As Action End Structure", (OriginatingProjectLanguage.CSharp, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", (OriginatingProjectLanguage.VisualBasic, true) => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {FeaturesResources.location_unknown} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct S {{ public event Action [|E|] {{ add {{ }} remove {{ }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 9)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", _ => throw ExceptionUtilities.Unreachable, }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, ToLanguageName(language), expected, allowDecompilation: allowDecompilation); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Type() { var metadata = @"using System; public class TestType<T> where T : notnull { }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new [|TestType|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|TestType|]<T> where T : notnull {{ public TestType(); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Method() { var metadata = @"using System; public class TestType { public void M<T>() where T : notnull { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M|]&lt;int&gt;(); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M|]<T>() where T : notnull; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNotNullCSharpConstraint_Delegate() { var metadata = @"using System; public delegate void D<T>() where T : notnull;"; var sourceWithSymbolReference = @" class C { void M([|D|]&lt;int&gt; lambda) { } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public delegate void [|D|]<T>() where T : notnull;"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable1() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); #nullable enable }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable2() { var metadata = @" using System; public class TestType { public void M1(string s) { } #nullable enable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); #nullable disable public void [|M1|](string s); #nullable enable public void M2(string s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable3() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } public void M3(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); public void M3(string s); #nullable enable }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable4() { var metadata = @" #nullable enable using System; public class TestType { public void M1(ICloneable s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable using System; public class TestType {{ public TestType(); public void [|M1|](ICloneable s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable5() { var metadata = @" #nullable enable using System; public class TestType { public void M1(ICloneable s) { #nullable disable } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable using System; public class TestType {{ public TestType(); public void [|M1|](ICloneable s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable6() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T? s) where T : class { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|]<T>(T? s) where T : class; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable7() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) where T : class { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|]<T>(T s) where T : class; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable8() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T? s) where T : struct { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|]((int?)0); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T? s) where T : struct; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable9() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) where T : struct { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](0); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s) where T : struct; }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable10() { var metadata = @" #nullable enable using System; public class TestType { public void M1<T>(T s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable11() { var metadata = @" using System; public class TestType { public void M1<T>(T s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](""""); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|]<T>(T s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable12() { var metadata = @" #nullable enable using System; namespace N { public class TestType { public void M1(string s) { } #nullable disable public void M2(string s) { } } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new N.TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable namespace N {{ public class TestType {{ public TestType(); public void [|M1|](string s); #nullable disable public void M2(string s); #nullable enable }} }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestNullableEnableDisable13() { var metadata = @" #nullable enable using System; public class TestType { public void M1(string s) { } #nullable disable public class Nested { public void NestedM(string s) { } } #nullable enable public void M2(string s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion #nullable enable public class TestType {{ public TestType(); public void [|M1|](string s); public void M2(string s); public class Nested {{ public Nested(); #nullable disable public void NestedM(string s); #nullable enable }} }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestDynamic1() { var metadata = @" using System; public class TestType { public void M1(dynamic s) { } }"; var sourceWithSymbolReference = @" class C { void M() { var obj = new TestType().[|M1|](null); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class TestType {{ public TestType(); public void [|M1|](dynamic s); }}"; using var context = TestContext.Create( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, languageVersion: "8", sourceWithSymbolReference: sourceWithSymbolReference, metadataLanguageVersion: "8"); var navigationSymbol = await context.GetNavigationSymbolAsync(); var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol); TestContext.VerifyResult(metadataAsSourceFile, expected); } [WorkItem(22431, "https://github.com/dotnet/roslyn/issues/22431")] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestCDATAComment() { var source = @" public enum BinaryOperatorKind { /// <summary> /// Represents the <![CDATA['<<']]> operator. /// </summary> LeftShift = 0x8, } "; var symbolName = "BinaryOperatorKind.LeftShift"; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum BinaryOperatorKind {{ // // {FeaturesResources.Summary_colon} // Represents the '<<' operator. [|LeftShift|] = 8 }}"; await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS, includeXmlDocComments: true); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/Core/Def/IInvisibleEditor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices { internal interface IInvisibleEditor : IDisposable { ITextBuffer TextBuffer { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices { internal interface IInvisibleEditor : IDisposable { ITextBuffer TextBuffer { get; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationWithAnalyzersOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Options to configure analyzer execution within <see cref="CompilationWithAnalyzers"/>. /// </summary> public sealed class CompilationWithAnalyzersOptions { private readonly AnalyzerOptions? _options; private readonly Action<Exception, DiagnosticAnalyzer, Diagnostic>? _onAnalyzerException; private readonly Func<Exception, bool>? _analyzerExceptionFilter; private readonly bool _concurrentAnalysis; private readonly bool _logAnalyzerExecutionTime; private readonly bool _reportSuppressedDiagnostics; /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>s. /// </summary> public AnalyzerOptions? Options => _options; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception. /// </summary> public Action<Exception, DiagnosticAnalyzer, Diagnostic>? OnAnalyzerException => _onAnalyzerException; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception as an exception filter. /// </summary> public Func<Exception, bool>? AnalyzerExceptionFilter => _analyzerExceptionFilter; /// <summary> /// Flag indicating whether analysis can be performed concurrently on multiple threads. /// </summary> public bool ConcurrentAnalysis => _concurrentAnalysis; /// <summary> /// Flag indicating whether analyzer execution time should be logged. /// </summary> public bool LogAnalyzerExecutionTime => _logAnalyzerExecutionTime; /// <summary> /// Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported. /// </summary> public bool ReportSuppressedDiagnostics => _reportSuppressedDiagnostics; /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics, analyzerExceptionFilter: null) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="analyzerExceptionFilter">Action to invoke if an analyzer throws an exception as an exception filter.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions? options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics, Func<Exception, bool>? analyzerExceptionFilter) { _options = options; _onAnalyzerException = onAnalyzerException; _analyzerExceptionFilter = analyzerExceptionFilter; _concurrentAnalysis = concurrentAnalysis; _logAnalyzerExecutionTime = logAnalyzerExecutionTime; _reportSuppressedDiagnostics = reportSuppressedDiagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Options to configure analyzer execution within <see cref="CompilationWithAnalyzers"/>. /// </summary> public sealed class CompilationWithAnalyzersOptions { private readonly AnalyzerOptions? _options; private readonly Action<Exception, DiagnosticAnalyzer, Diagnostic>? _onAnalyzerException; private readonly Func<Exception, bool>? _analyzerExceptionFilter; private readonly bool _concurrentAnalysis; private readonly bool _logAnalyzerExecutionTime; private readonly bool _reportSuppressedDiagnostics; /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>s. /// </summary> public AnalyzerOptions? Options => _options; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception. /// </summary> public Action<Exception, DiagnosticAnalyzer, Diagnostic>? OnAnalyzerException => _onAnalyzerException; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception as an exception filter. /// </summary> public Func<Exception, bool>? AnalyzerExceptionFilter => _analyzerExceptionFilter; /// <summary> /// Flag indicating whether analysis can be performed concurrently on multiple threads. /// </summary> public bool ConcurrentAnalysis => _concurrentAnalysis; /// <summary> /// Flag indicating whether analyzer execution time should be logged. /// </summary> public bool LogAnalyzerExecutionTime => _logAnalyzerExecutionTime; /// <summary> /// Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported. /// </summary> public bool ReportSuppressedDiagnostics => _reportSuppressedDiagnostics; /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics, analyzerExceptionFilter: null) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="analyzerExceptionFilter">Action to invoke if an analyzer throws an exception as an exception filter.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions? options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics, Func<Exception, bool>? analyzerExceptionFilter) { _options = options; _onAnalyzerException = onAnalyzerException; _analyzerExceptionFilter = analyzerExceptionFilter; _concurrentAnalysis = concurrentAnalysis; _logAnalyzerExecutionTime = logAnalyzerExecutionTime; _reportSuppressedDiagnostics = reportSuppressedDiagnostics; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/Core.Wpf/Preview/PreviewReferenceHighlightingTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using System; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// Special tagger we use for previews that is told precisely which spans to /// reference highlight. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewWrittenReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewWrittenReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewDefinitionHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewDefinitionHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.Instance) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using System; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// Special tagger we use for previews that is told precisely which spans to /// reference highlight. /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey, ReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewWrittenReferenceHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewWrittenReferenceHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey, WrittenReferenceHighlightTag.Instance) { } } [Export(typeof(ITaggerProvider))] [TagType(typeof(NavigableHighlightTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewDefinitionHighlightingTaggerProvider : AbstractPreviewTaggerProvider<NavigableHighlightTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewDefinitionHighlightingTaggerProvider() : base(PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey, DefinitionHighlightTag.Instance) { } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Test/Core/Diagnostics/ThrowingDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public class ThrowingDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct { [Serializable] public class DeliberateException : Exception { public DeliberateException() { } protected DeliberateException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new NotImplementedException(); } public override string Message { get { return "If this goes unhandled, our diagnostics engine is susceptible to malicious analyzers"; } } } private readonly List<string> _throwOnList = new List<string>(); public bool Thrown { get; private set; } public void ThrowOn(string method) { _throwOnList.Add(method); } protected override void OnAbstractMember(string abstractMemberName, SyntaxNode node, ISymbol symbol, string methodName) { if (_throwOnList.Contains(methodName)) { Thrown = true; throw new DeliberateException(); } } public static void VerifyAnalyzerEngineIsSafeAgainstExceptions(Func<DiagnosticAnalyzer, IEnumerable<Diagnostic>> runAnalysis) { VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(runAnalysis).Wait(); } public static async Task VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(Func<DiagnosticAnalyzer, IEnumerable<Diagnostic>> runAnalysis) { await VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(a => Task.FromResult(runAnalysis(a))); } public static async Task VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(Func<DiagnosticAnalyzer, Task<IEnumerable<Diagnostic>>> runAnalysis) { var handled = new bool?[AllAnalyzerMemberNames.Length]; for (int i = 0; i < AllAnalyzerMemberNames.Length; i++) { var member = AllAnalyzerMemberNames[i]; var analyzer = new ThrowingDiagnosticAnalyzer<TLanguageKindEnum>(); analyzer.ThrowOn(member); try { var diagnostics = (await runAnalysis(analyzer)).Distinct(); handled[i] = analyzer.Thrown ? true : (bool?)null; if (analyzer.Thrown) { Assert.True(diagnostics.Any(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic)); } else { Assert.False(diagnostics.Any(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic)); } } catch (DeliberateException) { handled[i] = false; } } var membersHandled = AllAnalyzerMemberNames.Zip(handled, (m, h) => new { Member = m, Handled = h }); Assert.True(!handled.Any(h => h == false) && handled.Any(h => true), Environment.NewLine + " Exceptions thrown by analyzers in these members were *NOT* handled:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == false).Select(mh => mh.Member)) + Environment.NewLine + Environment.NewLine + " Exceptions thrown from these members were handled gracefully:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == true).Select(mh => mh.Member)) + Environment.NewLine + Environment.NewLine + " These members were not called/accessed by analyzer engine:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == null).Select(mh => mh.Member))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public class ThrowingDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct { [Serializable] public class DeliberateException : Exception { public DeliberateException() { } protected DeliberateException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new NotImplementedException(); } public override string Message { get { return "If this goes unhandled, our diagnostics engine is susceptible to malicious analyzers"; } } } private readonly List<string> _throwOnList = new List<string>(); public bool Thrown { get; private set; } public void ThrowOn(string method) { _throwOnList.Add(method); } protected override void OnAbstractMember(string abstractMemberName, SyntaxNode node, ISymbol symbol, string methodName) { if (_throwOnList.Contains(methodName)) { Thrown = true; throw new DeliberateException(); } } public static void VerifyAnalyzerEngineIsSafeAgainstExceptions(Func<DiagnosticAnalyzer, IEnumerable<Diagnostic>> runAnalysis) { VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(runAnalysis).Wait(); } public static async Task VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(Func<DiagnosticAnalyzer, IEnumerable<Diagnostic>> runAnalysis) { await VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(a => Task.FromResult(runAnalysis(a))); } public static async Task VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(Func<DiagnosticAnalyzer, Task<IEnumerable<Diagnostic>>> runAnalysis) { var handled = new bool?[AllAnalyzerMemberNames.Length]; for (int i = 0; i < AllAnalyzerMemberNames.Length; i++) { var member = AllAnalyzerMemberNames[i]; var analyzer = new ThrowingDiagnosticAnalyzer<TLanguageKindEnum>(); analyzer.ThrowOn(member); try { var diagnostics = (await runAnalysis(analyzer)).Distinct(); handled[i] = analyzer.Thrown ? true : (bool?)null; if (analyzer.Thrown) { Assert.True(diagnostics.Any(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic)); } else { Assert.False(diagnostics.Any(AnalyzerExecutor.IsAnalyzerExceptionDiagnostic)); } } catch (DeliberateException) { handled[i] = false; } } var membersHandled = AllAnalyzerMemberNames.Zip(handled, (m, h) => new { Member = m, Handled = h }); Assert.True(!handled.Any(h => h == false) && handled.Any(h => true), Environment.NewLine + " Exceptions thrown by analyzers in these members were *NOT* handled:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == false).Select(mh => mh.Member)) + Environment.NewLine + Environment.NewLine + " Exceptions thrown from these members were handled gracefully:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == true).Select(mh => mh.Member)) + Environment.NewLine + Environment.NewLine + " These members were not called/accessed by analyzer engine:" + Environment.NewLine + string.Join(Environment.NewLine, membersHandled.Where(mh => mh.Handled == null).Select(mh => mh.Member))); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.DeclarationAnalysisData.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class AnalyzerDriver { internal sealed class DeclarationAnalysisData { public DeclarationAnalysisData( SyntaxNode declaringReferenceSyntax, SyntaxNode topmostNodeForAnalysis, ImmutableArray<DeclarationInfo> declarationsInNodeBuilder, ImmutableArray<SyntaxNode> descendantNodesToAnalyze, bool isPartialAnalysis) { DeclaringReferenceSyntax = declaringReferenceSyntax; TopmostNodeForAnalysis = topmostNodeForAnalysis; DeclarationsInNode = declarationsInNodeBuilder; DescendantNodesToAnalyze = descendantNodesToAnalyze; IsPartialAnalysis = isPartialAnalysis; } /// <summary> /// GetSyntax() for the given SyntaxReference. /// </summary> public SyntaxNode DeclaringReferenceSyntax { get; } /// <summary> /// Topmost declaration node for analysis. /// </summary> public SyntaxNode TopmostNodeForAnalysis { get; } /// <summary> /// All member declarations within the declaration. /// </summary> public ImmutableArray<DeclarationInfo> DeclarationsInNode { get; } /// <summary> /// All descendant nodes for syntax node actions. /// </summary> public ImmutableArray<SyntaxNode> DescendantNodesToAnalyze { get; } /// <summary> /// Flag indicating if this is a partial analysis. /// </summary> public bool IsPartialAnalysis { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class AnalyzerDriver { internal sealed class DeclarationAnalysisData { public DeclarationAnalysisData( SyntaxNode declaringReferenceSyntax, SyntaxNode topmostNodeForAnalysis, ImmutableArray<DeclarationInfo> declarationsInNodeBuilder, ImmutableArray<SyntaxNode> descendantNodesToAnalyze, bool isPartialAnalysis) { DeclaringReferenceSyntax = declaringReferenceSyntax; TopmostNodeForAnalysis = topmostNodeForAnalysis; DeclarationsInNode = declarationsInNodeBuilder; DescendantNodesToAnalyze = descendantNodesToAnalyze; IsPartialAnalysis = isPartialAnalysis; } /// <summary> /// GetSyntax() for the given SyntaxReference. /// </summary> public SyntaxNode DeclaringReferenceSyntax { get; } /// <summary> /// Topmost declaration node for analysis. /// </summary> public SyntaxNode TopmostNodeForAnalysis { get; } /// <summary> /// All member declarations within the declaration. /// </summary> public ImmutableArray<DeclarationInfo> DeclarationsInNode { get; } /// <summary> /// All descendant nodes for syntax node actions. /// </summary> public ImmutableArray<SyntaxNode> DescendantNodesToAnalyze { get; } /// <summary> /// Flag indicating if this is a partial analysis. /// </summary> public bool IsPartialAnalysis { get; } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/MetadataReader/TypeNameDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis { internal abstract class TypeNameDecoder<ModuleSymbol, TypeSymbol> where ModuleSymbol : class where TypeSymbol : class { private readonly SymbolFactory<ModuleSymbol, TypeSymbol> _factory; protected readonly ModuleSymbol moduleSymbol; internal TypeNameDecoder(SymbolFactory<ModuleSymbol, TypeSymbol> factory, ModuleSymbol moduleSymbol) { _factory = factory; this.moduleSymbol = moduleSymbol; } protected abstract bool IsContainingAssembly(AssemblyIdentity identity); /// <summary> /// Lookup a type defined in this module. /// </summary> protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType); /// <summary> /// Lookup a type defined in referenced assembly. /// </summary> protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(int referencedAssemblyIndex, ref MetadataTypeName emittedName); protected abstract TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName); /// <summary> /// Given the identity of an assembly referenced by this module, finds /// the index of that assembly in the list of assemblies referenced by /// the current module. /// </summary> protected abstract int GetIndexOfReferencedAssembly(AssemblyIdentity identity); internal TypeSymbol GetTypeSymbolForSerializedType(string s) { if (string.IsNullOrEmpty(s)) { return GetUnsupportedMetadataTypeSymbol(); } MetadataHelpers.AssemblyQualifiedTypeName fullName = MetadataHelpers.DecodeTypeName(s); bool refersToNoPiaLocalType; return GetTypeSymbol(fullName, out refersToNoPiaLocalType); } protected TypeSymbol GetUnsupportedMetadataTypeSymbol(BadImageFormatException exception = null) { return _factory.GetUnsupportedMetadataTypeSymbol(this.moduleSymbol, exception); } protected TypeSymbol GetSZArrayTypeSymbol(TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers) { return _factory.GetSZArrayTypeSymbol(this.moduleSymbol, elementType, customModifiers); } protected TypeSymbol GetMDArrayTypeSymbol(int rank, TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds) { return _factory.GetMDArrayTypeSymbol(this.moduleSymbol, rank, elementType, customModifiers, sizes, lowerBounds); } protected TypeSymbol MakePointerTypeSymbol(TypeSymbol type, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers) { return _factory.MakePointerTypeSymbol(this.moduleSymbol, type, customModifiers); } protected TypeSymbol MakeFunctionPointerTypeSymbol(Cci.CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamInfos) { return _factory.MakeFunctionPointerTypeSymbol(callingConvention, retAndParamInfos); } protected TypeSymbol GetSpecialType(SpecialType specialType) { return _factory.GetSpecialType(this.moduleSymbol, specialType); } protected TypeSymbol SystemTypeSymbol { get { return _factory.GetSystemTypeSymbol(this.moduleSymbol); } } protected TypeSymbol GetEnumUnderlyingType(TypeSymbol type) { return _factory.GetEnumUnderlyingType(this.moduleSymbol, type); } protected Microsoft.Cci.PrimitiveTypeCode GetPrimitiveTypeCode(TypeSymbol type) { return _factory.GetPrimitiveTypeCode(this.moduleSymbol, type); } protected TypeSymbol SubstituteWithUnboundIfGeneric(TypeSymbol type) { return _factory.MakeUnboundIfGeneric(this.moduleSymbol, type); } protected TypeSymbol SubstituteTypeParameters(TypeSymbol genericType, ImmutableArray<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>> arguments, ImmutableArray<bool> refersToNoPiaLocalType) { return _factory.SubstituteTypeParameters(this.moduleSymbol, genericType, arguments, refersToNoPiaLocalType); } internal TypeSymbol GetTypeSymbol(MetadataHelpers.AssemblyQualifiedTypeName fullName, out bool refersToNoPiaLocalType) { // // Section 23.3 (Custom Attributes) of CLI Spec Partition II: // // If the parameter kind is System.Type, (also, the middle line in above diagram) its value is // stored as a SerString (as defined in the previous paragraph), representing its canonical name. // The canonical name is its full type name, followed optionally by the assembly where it is defined, // its version, culture and public-key-token. If the assembly name is omitted, the CLI looks first // in the current assembly, and then in the system library (mscorlib); in these two special cases, // it is permitted to omit the assembly-name, version, culture and public-key-token. int referencedAssemblyIndex; if (fullName.AssemblyName != null) { AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(fullName.AssemblyName, out identity)) { refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } // the assembly name has to be a full name: referencedAssemblyIndex = GetIndexOfReferencedAssembly(identity); if (referencedAssemblyIndex == -1) { // In rare cases (e.g. assemblies emitted by Reflection.Emit) the identity // might be the identity of the containing assembly. The metadata spec doesn't disallow this. if (!this.IsContainingAssembly(identity)) { refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } } } else { // Use this assembly referencedAssemblyIndex = -1; } // Find the top level type Debug.Assert(MetadataHelpers.IsValidMetadataIdentifier(fullName.TopLevelType)); var mdName = MetadataTypeName.FromFullName(fullName.TopLevelType); TypeSymbol container = LookupTopLevelTypeDefSymbol(ref mdName, referencedAssemblyIndex, out refersToNoPiaLocalType); // Process any nested types if (fullName.NestedTypes != null) { if (refersToNoPiaLocalType) { // Types nested into local types are not supported. refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } for (int i = 0; i < fullName.NestedTypes.Length; i++) { Debug.Assert(MetadataHelpers.IsValidMetadataIdentifier(fullName.NestedTypes[i])); mdName = MetadataTypeName.FromTypeName(fullName.NestedTypes[i]); // Find nested type in the container container = LookupNestedTypeDefSymbol(container, ref mdName); } } // Substitute type arguments if any if (fullName.TypeArguments != null) { ImmutableArray<bool> argumentRefersToNoPiaLocalType; var typeArguments = ResolveTypeArguments(fullName.TypeArguments, out argumentRefersToNoPiaLocalType); container = SubstituteTypeParameters(container, typeArguments, argumentRefersToNoPiaLocalType); foreach (bool flag in argumentRefersToNoPiaLocalType) { if (flag) { refersToNoPiaLocalType = true; break; } } } else { container = SubstituteWithUnboundIfGeneric(container); } for (int i = 0; i < fullName.PointerCount; i++) { container = MakePointerTypeSymbol(container, ImmutableArray<ModifierInfo<TypeSymbol>>.Empty); } // Process any array type ranks if (fullName.ArrayRanks != null) { foreach (int rank in fullName.ArrayRanks) { Debug.Assert(rank >= 0); container = rank == 0 ? GetSZArrayTypeSymbol(container, default(ImmutableArray<ModifierInfo<TypeSymbol>>)) : GetMDArrayTypeSymbol(rank, container, default(ImmutableArray<ModifierInfo<TypeSymbol>>), ImmutableArray<int>.Empty, default(ImmutableArray<int>)); } } return container; } private ImmutableArray<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>> ResolveTypeArguments(MetadataHelpers.AssemblyQualifiedTypeName[] arguments, out ImmutableArray<bool> refersToNoPiaLocalType) { int count = arguments.Length; var typeArgumentsBuilder = ArrayBuilder<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>>.GetInstance(count); var refersToNoPiaBuilder = ArrayBuilder<bool>.GetInstance(count); foreach (var argument in arguments) { bool refersToNoPia; typeArgumentsBuilder.Add(new KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>(GetTypeSymbol(argument, out refersToNoPia), ImmutableArray<ModifierInfo<TypeSymbol>>.Empty)); refersToNoPiaBuilder.Add(refersToNoPia); } refersToNoPiaLocalType = refersToNoPiaBuilder.ToImmutableAndFree(); return typeArgumentsBuilder.ToImmutableAndFree(); } private TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, int referencedAssemblyIndex, out bool isNoPiaLocalType) { TypeSymbol container; if (referencedAssemblyIndex >= 0) { // Find top level type in referenced assembly isNoPiaLocalType = false; container = LookupTopLevelTypeDefSymbol(referencedAssemblyIndex, ref emittedName); } else { // TODO : lookup in mscorlib // Find top level type in this assembly or mscorlib: container = LookupTopLevelTypeDefSymbol(ref emittedName, out isNoPiaLocalType); } return container; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis { internal abstract class TypeNameDecoder<ModuleSymbol, TypeSymbol> where ModuleSymbol : class where TypeSymbol : class { private readonly SymbolFactory<ModuleSymbol, TypeSymbol> _factory; protected readonly ModuleSymbol moduleSymbol; internal TypeNameDecoder(SymbolFactory<ModuleSymbol, TypeSymbol> factory, ModuleSymbol moduleSymbol) { _factory = factory; this.moduleSymbol = moduleSymbol; } protected abstract bool IsContainingAssembly(AssemblyIdentity identity); /// <summary> /// Lookup a type defined in this module. /// </summary> protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, out bool isNoPiaLocalType); /// <summary> /// Lookup a type defined in referenced assembly. /// </summary> protected abstract TypeSymbol LookupTopLevelTypeDefSymbol(int referencedAssemblyIndex, ref MetadataTypeName emittedName); protected abstract TypeSymbol LookupNestedTypeDefSymbol(TypeSymbol container, ref MetadataTypeName emittedName); /// <summary> /// Given the identity of an assembly referenced by this module, finds /// the index of that assembly in the list of assemblies referenced by /// the current module. /// </summary> protected abstract int GetIndexOfReferencedAssembly(AssemblyIdentity identity); internal TypeSymbol GetTypeSymbolForSerializedType(string s) { if (string.IsNullOrEmpty(s)) { return GetUnsupportedMetadataTypeSymbol(); } MetadataHelpers.AssemblyQualifiedTypeName fullName = MetadataHelpers.DecodeTypeName(s); bool refersToNoPiaLocalType; return GetTypeSymbol(fullName, out refersToNoPiaLocalType); } protected TypeSymbol GetUnsupportedMetadataTypeSymbol(BadImageFormatException exception = null) { return _factory.GetUnsupportedMetadataTypeSymbol(this.moduleSymbol, exception); } protected TypeSymbol GetSZArrayTypeSymbol(TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers) { return _factory.GetSZArrayTypeSymbol(this.moduleSymbol, elementType, customModifiers); } protected TypeSymbol GetMDArrayTypeSymbol(int rank, TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds) { return _factory.GetMDArrayTypeSymbol(this.moduleSymbol, rank, elementType, customModifiers, sizes, lowerBounds); } protected TypeSymbol MakePointerTypeSymbol(TypeSymbol type, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers) { return _factory.MakePointerTypeSymbol(this.moduleSymbol, type, customModifiers); } protected TypeSymbol MakeFunctionPointerTypeSymbol(Cci.CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamInfos) { return _factory.MakeFunctionPointerTypeSymbol(callingConvention, retAndParamInfos); } protected TypeSymbol GetSpecialType(SpecialType specialType) { return _factory.GetSpecialType(this.moduleSymbol, specialType); } protected TypeSymbol SystemTypeSymbol { get { return _factory.GetSystemTypeSymbol(this.moduleSymbol); } } protected TypeSymbol GetEnumUnderlyingType(TypeSymbol type) { return _factory.GetEnumUnderlyingType(this.moduleSymbol, type); } protected Microsoft.Cci.PrimitiveTypeCode GetPrimitiveTypeCode(TypeSymbol type) { return _factory.GetPrimitiveTypeCode(this.moduleSymbol, type); } protected TypeSymbol SubstituteWithUnboundIfGeneric(TypeSymbol type) { return _factory.MakeUnboundIfGeneric(this.moduleSymbol, type); } protected TypeSymbol SubstituteTypeParameters(TypeSymbol genericType, ImmutableArray<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>> arguments, ImmutableArray<bool> refersToNoPiaLocalType) { return _factory.SubstituteTypeParameters(this.moduleSymbol, genericType, arguments, refersToNoPiaLocalType); } internal TypeSymbol GetTypeSymbol(MetadataHelpers.AssemblyQualifiedTypeName fullName, out bool refersToNoPiaLocalType) { // // Section 23.3 (Custom Attributes) of CLI Spec Partition II: // // If the parameter kind is System.Type, (also, the middle line in above diagram) its value is // stored as a SerString (as defined in the previous paragraph), representing its canonical name. // The canonical name is its full type name, followed optionally by the assembly where it is defined, // its version, culture and public-key-token. If the assembly name is omitted, the CLI looks first // in the current assembly, and then in the system library (mscorlib); in these two special cases, // it is permitted to omit the assembly-name, version, culture and public-key-token. int referencedAssemblyIndex; if (fullName.AssemblyName != null) { AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(fullName.AssemblyName, out identity)) { refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } // the assembly name has to be a full name: referencedAssemblyIndex = GetIndexOfReferencedAssembly(identity); if (referencedAssemblyIndex == -1) { // In rare cases (e.g. assemblies emitted by Reflection.Emit) the identity // might be the identity of the containing assembly. The metadata spec doesn't disallow this. if (!this.IsContainingAssembly(identity)) { refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } } } else { // Use this assembly referencedAssemblyIndex = -1; } // Find the top level type Debug.Assert(MetadataHelpers.IsValidMetadataIdentifier(fullName.TopLevelType)); var mdName = MetadataTypeName.FromFullName(fullName.TopLevelType); TypeSymbol container = LookupTopLevelTypeDefSymbol(ref mdName, referencedAssemblyIndex, out refersToNoPiaLocalType); // Process any nested types if (fullName.NestedTypes != null) { if (refersToNoPiaLocalType) { // Types nested into local types are not supported. refersToNoPiaLocalType = false; return GetUnsupportedMetadataTypeSymbol(); } for (int i = 0; i < fullName.NestedTypes.Length; i++) { Debug.Assert(MetadataHelpers.IsValidMetadataIdentifier(fullName.NestedTypes[i])); mdName = MetadataTypeName.FromTypeName(fullName.NestedTypes[i]); // Find nested type in the container container = LookupNestedTypeDefSymbol(container, ref mdName); } } // Substitute type arguments if any if (fullName.TypeArguments != null) { ImmutableArray<bool> argumentRefersToNoPiaLocalType; var typeArguments = ResolveTypeArguments(fullName.TypeArguments, out argumentRefersToNoPiaLocalType); container = SubstituteTypeParameters(container, typeArguments, argumentRefersToNoPiaLocalType); foreach (bool flag in argumentRefersToNoPiaLocalType) { if (flag) { refersToNoPiaLocalType = true; break; } } } else { container = SubstituteWithUnboundIfGeneric(container); } for (int i = 0; i < fullName.PointerCount; i++) { container = MakePointerTypeSymbol(container, ImmutableArray<ModifierInfo<TypeSymbol>>.Empty); } // Process any array type ranks if (fullName.ArrayRanks != null) { foreach (int rank in fullName.ArrayRanks) { Debug.Assert(rank >= 0); container = rank == 0 ? GetSZArrayTypeSymbol(container, default(ImmutableArray<ModifierInfo<TypeSymbol>>)) : GetMDArrayTypeSymbol(rank, container, default(ImmutableArray<ModifierInfo<TypeSymbol>>), ImmutableArray<int>.Empty, default(ImmutableArray<int>)); } } return container; } private ImmutableArray<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>> ResolveTypeArguments(MetadataHelpers.AssemblyQualifiedTypeName[] arguments, out ImmutableArray<bool> refersToNoPiaLocalType) { int count = arguments.Length; var typeArgumentsBuilder = ArrayBuilder<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>>.GetInstance(count); var refersToNoPiaBuilder = ArrayBuilder<bool>.GetInstance(count); foreach (var argument in arguments) { bool refersToNoPia; typeArgumentsBuilder.Add(new KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>(GetTypeSymbol(argument, out refersToNoPia), ImmutableArray<ModifierInfo<TypeSymbol>>.Empty)); refersToNoPiaBuilder.Add(refersToNoPia); } refersToNoPiaLocalType = refersToNoPiaBuilder.ToImmutableAndFree(); return typeArgumentsBuilder.ToImmutableAndFree(); } private TypeSymbol LookupTopLevelTypeDefSymbol(ref MetadataTypeName emittedName, int referencedAssemblyIndex, out bool isNoPiaLocalType) { TypeSymbol container; if (referencedAssemblyIndex >= 0) { // Find top level type in referenced assembly isNoPiaLocalType = false; container = LookupTopLevelTypeDefSymbol(referencedAssemblyIndex, ref emittedName); } else { // TODO : lookup in mscorlib // Find top level type in this assembly or mscorlib: container = LookupTopLevelTypeDefSymbol(ref emittedName, out isNoPiaLocalType); } return container; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Features/Core/Portable/UnsealClass/AbstractUnsealClassCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnsealClass { internal abstract class AbstractUnsealClassCodeFixProvider : CodeFixProvider { protected abstract string TitleFormat { get; } public override FixAllProvider GetFixAllProvider() { // This code fix addresses a very specific compiler error. It's unlikely there will be more than 1 of them at a time. return null; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var node = syntaxRoot.FindNode(context.Span, getInnermostNodeForTie: true); if (semanticModel.GetSymbolInfo(node, cancellationToken).Symbol is INamedTypeSymbol type && type.TypeKind == TypeKind.Class && type.IsSealed && !type.IsStatic) { var definition = await SymbolFinder.FindSourceDefinitionAsync( type, document.Project.Solution, cancellationToken).ConfigureAwait(false); if (definition != null && definition.DeclaringSyntaxReferences.Length > 0) { context.RegisterCodeFix( new MyCodeAction( string.Format(TitleFormat, type.Name), c => UnsealDeclarationsAsync(document.Project.Solution, definition.DeclaringSyntaxReferences, c)), context.Diagnostics); } } } private static async Task<Solution> UnsealDeclarationsAsync( Solution solution, ImmutableArray<SyntaxReference> declarationReferences, CancellationToken cancellationToken) { foreach (var (documentId, syntaxReferences) in declarationReferences.GroupBy(reference => solution.GetDocumentId(reference.SyntaxTree))) { var document = solution.GetDocument(documentId); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var editor = new SyntaxEditor(root, generator); foreach (var syntaxReference in syntaxReferences) { var declaration = await syntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var modifiers = generator.GetModifiers(declaration); if (modifiers.IsSealed) { var newDeclaration = generator.WithModifiers(declaration, modifiers.WithIsSealed(false)); editor.ReplaceNode(declaration, newDeclaration); } } solution = solution.WithDocumentSyntaxRoot(documentId, editor.GetChangedRoot()); } return solution; } private sealed class MyCodeAction : CodeAction.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnsealClass { internal abstract class AbstractUnsealClassCodeFixProvider : CodeFixProvider { protected abstract string TitleFormat { get; } public override FixAllProvider GetFixAllProvider() { // This code fix addresses a very specific compiler error. It's unlikely there will be more than 1 of them at a time. return null; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var node = syntaxRoot.FindNode(context.Span, getInnermostNodeForTie: true); if (semanticModel.GetSymbolInfo(node, cancellationToken).Symbol is INamedTypeSymbol type && type.TypeKind == TypeKind.Class && type.IsSealed && !type.IsStatic) { var definition = await SymbolFinder.FindSourceDefinitionAsync( type, document.Project.Solution, cancellationToken).ConfigureAwait(false); if (definition != null && definition.DeclaringSyntaxReferences.Length > 0) { context.RegisterCodeFix( new MyCodeAction( string.Format(TitleFormat, type.Name), c => UnsealDeclarationsAsync(document.Project.Solution, definition.DeclaringSyntaxReferences, c)), context.Diagnostics); } } } private static async Task<Solution> UnsealDeclarationsAsync( Solution solution, ImmutableArray<SyntaxReference> declarationReferences, CancellationToken cancellationToken) { foreach (var (documentId, syntaxReferences) in declarationReferences.GroupBy(reference => solution.GetDocumentId(reference.SyntaxTree))) { var document = solution.GetDocument(documentId); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var editor = new SyntaxEditor(root, generator); foreach (var syntaxReference in syntaxReferences) { var declaration = await syntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var modifiers = generator.GetModifiers(declaration); if (modifiers.IsSealed) { var newDeclaration = generator.WithModifiers(declaration, modifiers.WithIsSealed(false)); editor.ReplaceNode(declaration, newDeclaration); } } solution = solution.WithDocumentSyntaxRoot(documentId, editor.GetChangedRoot()); } return solution; } private sealed class MyCodeAction : CodeAction.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/Core/Implementation/Diagnostics/ClassificationTypeDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { internal sealed class ClassificationTypeDefinitions { public const string UnnecessaryCode = "unnecessary code"; [Export] [Name(UnnecessaryCode)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal ClassificationTypeDefinition UnnecessaryCodeTypeDefinition { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics { internal sealed class ClassificationTypeDefinitions { public const string UnnecessaryCode = "unnecessary code"; [Export] [Name(UnnecessaryCode)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal ClassificationTypeDefinition UnnecessaryCodeTypeDefinition { get; set; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Tools/IdeBenchmarks/Properties/AssemblyInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using BenchmarkDotNet.Attributes; using IdeBenchmarks; [assembly: Config(typeof(MemoryDiagnoserConfig))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using BenchmarkDotNet.Attributes; using IdeBenchmarks; [assembly: Config(typeof(MemoryDiagnoserConfig))]
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Features/Core/Portable/GenerateMember/GenerateEnumMember/IGenerateEnumMemberService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal interface IGenerateEnumMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateEnumMemberAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal interface IGenerateEnumMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateEnumMemberAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/CSharpTest2/Recommendations/VirtualKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VirtualKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace() { await VerifyAbsenceAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeDeclaration() { await VerifyAbsenceAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateDeclaration() { await VerifyAbsenceAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync( @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync( @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAssemblyAttribute() { await VerifyAbsenceAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStruct() { await VerifyAbsenceAsync(@"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStatic() { await VerifyAbsenceAsync(@"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPrivate() { await VerifyAbsenceAsync(@"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstract() { await VerifyAbsenceAsync(@"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtual() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverride() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealed() { await VerifyAbsenceAsync(@"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivateProtected() { await VerifyKeywordAsync( @"class C { private protected $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VirtualKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace() { await VerifyAbsenceAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeDeclaration() { await VerifyAbsenceAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateDeclaration() { await VerifyAbsenceAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodInClass() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFieldInClass() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyInClass() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync( @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync( @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAssemblyAttribute() { await VerifyAbsenceAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStruct() { await VerifyAbsenceAsync(@"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStatic() { await VerifyAbsenceAsync(@"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPrivate() { await VerifyAbsenceAsync(@"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstract() { await VerifyAbsenceAsync(@"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtual() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverride() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealed() { await VerifyAbsenceAsync(@"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterAccessibility() { await VerifyAbsenceAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivateProtected() { await VerifyKeywordAsync( @"class C { private protected $$"); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/Core.Wpf/GlyphExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Wpf { internal static class GlyphExtensions { public static ImageMoniker GetImageMoniker(this Glyph glyph) { var imageId = glyph.GetImageId(); return new ImageMoniker() { Guid = imageId.Guid, Id = imageId.Id }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Wpf { internal static class GlyphExtensions { public static ImageMoniker GetImageMoniker(this Glyph glyph) { var imageId = glyph.GetImageId(); return new ImageMoniker() { Guid = imageId.Guid, Id = imageId.Id }; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/CSharpTest/ConflictMarkerResolution/ConflictMarkerResolutionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ConflictMarkerResolution; using Microsoft.CodeAnalysis.CSharp.ConflictMarkerResolution; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConflictMarkerResolution { using VerifyCS = CSharpCodeFixVerifier<EmptyDiagnosticAnalyzer, CSharpResolveConflictMarkerCodeFixProvider>; public class ConflictMarkerResolutionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopCommentedOut() { var source = @" public class Class1 { public void M() { /* <<<<<<< dest * a thing */ {|CS8300:=======|} * another thing */ {|CS8300:>>>>>>>|} source // */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ // */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_MiddleAndBottomCommentedOut() { var source = @" public class Class1 { public void M() { {|CS8300:<<<<<<<|} dest /* * a thing ======= * * another thing >>>>>>> source */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" a""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" b""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtTopOfFile() { var source = @"{|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtBottomOfFile() { var source = @"{|CS8300:<<<<<<<|} working copy class X { } {|CS8300:=======|}"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program3 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll2() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll3() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program2 { } class Program3 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ConflictMarkerResolution; using Microsoft.CodeAnalysis.CSharp.ConflictMarkerResolution; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConflictMarkerResolution { using VerifyCS = CSharpCodeFixVerifier<EmptyDiagnosticAnalyzer, CSharpResolveConflictMarkerCodeFixProvider>; public class ConflictMarkerResolutionTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyTop_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeTop() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestEmptyBottom_TakeBottom() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom1_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBoth_WhitespaceInSection() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } {|CS8300:=======|} class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { static void Main(string[] args) { Program p; Console.WriteLine(""My section""); } } class Program2 { static void Main2(string[] args) { Program2 p; Console.WriteLine(""Their section""); } } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopCommentedOut() { var source = @" public class Class1 { public void M() { /* <<<<<<< dest * a thing */ {|CS8300:=======|} * another thing */ {|CS8300:>>>>>>>|} source // */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ // */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_MiddleAndBottomCommentedOut() { var source = @" public class Class1 { public void M() { {|CS8300:<<<<<<<|} dest /* * a thing ======= * * another thing >>>>>>> source */ } }"; var fixedSource = @" public class Class1 { public void M() { /* * a thing */ } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeTop_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" a""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestTakeBottom_TopInString() { var source = @" class X { void x() { var x = @"" <<<<<<< working copy a""; {|CS8300:=======|} b""; {|CS8300:>>>>>>>|} merge rev } }"; var fixedSource = @" class X { void x() { var x = @"" b""; } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 1, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtTopOfFile() { var source = @"{|CS8300:=======|} class X { } {|CS8300:>>>>>>>|} merge rev"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(23847, "https://github.com/dotnet/roslyn/issues/23847")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestMissingWithMiddleMarkerAtBottomOfFile() { var source = @"{|CS8300:<<<<<<<|} working copy class X { } {|CS8300:=======|}"; await new VerifyCS.Test { TestCode = source, FixedCode = source, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll1() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program3 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 0, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll2() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program2 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 1, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey, }.RunAsync(); } [WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)] public async Task TestFixAll3() { var source = @" using System; namespace N { {|CS8300:<<<<<<<|} This is mine! class Program { } {|CS8300:=======|} class Program2 { } {|CS8300:>>>>>>>|} This is theirs! {|CS8300:<<<<<<<|} This is mine! class Program3 { } {|CS8300:=======|} class Program4 { } {|CS8300:>>>>>>>|} This is theirs! }"; var fixedSource = @" using System; namespace N { class Program { } class Program2 { } class Program3 { } class Program4 { } }"; await new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, NumberOfIncrementalIterations = 2, CodeActionIndex = 2, CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey, }.RunAsync(); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/LiveShare/Impl/Client/RoslynLSPClientService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LiveShare; using Newtonsoft.Json.Linq; using Task = System.Threading.Tasks.Task; using LS = Microsoft.VisualStudio.LiveShare.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client { internal abstract class AbstractLspClientServiceFactory : ICollaborationServiceFactory { protected abstract string LanguageSpecificProviderName { get; } protected abstract RoslynLSPClientLifeTimeService LspClientLifeTimeService { get; } public LS.ILanguageServerClient ActiveLanguageServerClient { get; private set; } public Task<ICollaborationService> CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) { var languageServerGuestService = (LS.ILanguageServerGuestService)collaborationSession.GetService(typeof(LS.ILanguageServerGuestService)); collaborationSession.RemoteServicesChanged += (sender, e) => { // VS will expose a roslyn LSP server. var roslynLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(StringConstants.RoslynProviderName); // Newer versions of VS will expose language specific LSP servers for Roslyn. var languageSpecificLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(LanguageSpecificProviderName); // VSCode will expose a "any" LSP provider and both support roslyn languages. var anyLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(StringConstants.AnyProviderName); // For VS, Preferentially use the language specific server when it's available, otherwise fall back to the generic roslyn server. if (collaborationSession.RemoteServiceNames.Contains(languageSpecificLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(languageSpecificLspServerProviderName); } else if (collaborationSession.RemoteServiceNames.Contains(roslynLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(roslynLspServerProviderName); } else if (collaborationSession.RemoteServiceNames.Contains(anyLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(anyLspServerProviderName); } }; // Register Roslyn supported capabilities languageServerGuestService.RegisterClientMetadata( new string[] { StringConstants.TypeScriptLanguageName }, new LS.LanguageServerClientMetadata( true, JObject.FromObject(new ServerCapabilities { // Uses Roslyn client. DocumentSymbolProvider = true, // Uses LSP SDK client. DocumentLinkProvider = null, RenameProvider = false, DocumentOnTypeFormattingProvider = null, DocumentRangeFormattingProvider = false, DocumentFormattingProvider = false, CodeLensProvider = null, CodeActionProvider = false, ExecuteCommandProvider = null, WorkspaceSymbolProvider = false, DocumentHighlightProvider = false, ReferencesProvider = false, DefinitionProvider = false, SignatureHelpProvider = null, CompletionProvider = null, HoverProvider = false, TextDocumentSync = null, }))); var lifeTimeService = LspClientLifeTimeService; lifeTimeService.Disposed += (s, e) => { ActiveLanguageServerClient?.Dispose(); ActiveLanguageServerClient = null; }; return Task.FromResult<ICollaborationService>(lifeTimeService); } protected abstract class RoslynLSPClientLifeTimeService : ICollaborationService, IDisposable { public event EventHandler Disposed; public void Dispose() => Disposed?.Invoke(this, null); } } [Export] [ExportCollaborationService(typeof(CSharpLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class CSharpLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.CSharpProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new CSharpLSPClientLifeTimeService(); private class CSharpLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } [Export] [ExportCollaborationService(typeof(VisualBasicLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class VisualBasicLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.VisualBasicProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new VisualBasicLSPClientLifeTimeService(); private class VisualBasicLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } [Export] [ExportCollaborationService(typeof(TypeScriptLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class TypeScriptLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeScriptLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.TypeScriptProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new TypeScriptLSPClientLifeTimeService(); private class TypeScriptLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LiveShare; using Newtonsoft.Json.Linq; using Task = System.Threading.Tasks.Task; using LS = Microsoft.VisualStudio.LiveShare.LanguageServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client { internal abstract class AbstractLspClientServiceFactory : ICollaborationServiceFactory { protected abstract string LanguageSpecificProviderName { get; } protected abstract RoslynLSPClientLifeTimeService LspClientLifeTimeService { get; } public LS.ILanguageServerClient ActiveLanguageServerClient { get; private set; } public Task<ICollaborationService> CreateServiceAsync(CollaborationSession collaborationSession, CancellationToken cancellationToken) { var languageServerGuestService = (LS.ILanguageServerGuestService)collaborationSession.GetService(typeof(LS.ILanguageServerGuestService)); collaborationSession.RemoteServicesChanged += (sender, e) => { // VS will expose a roslyn LSP server. var roslynLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(StringConstants.RoslynProviderName); // Newer versions of VS will expose language specific LSP servers for Roslyn. var languageSpecificLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(LanguageSpecificProviderName); // VSCode will expose a "any" LSP provider and both support roslyn languages. var anyLspServerProviderName = LanguageServicesUtils.GetLanguageServerProviderServiceName(StringConstants.AnyProviderName); // For VS, Preferentially use the language specific server when it's available, otherwise fall back to the generic roslyn server. if (collaborationSession.RemoteServiceNames.Contains(languageSpecificLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(languageSpecificLspServerProviderName); } else if (collaborationSession.RemoteServiceNames.Contains(roslynLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(roslynLspServerProviderName); } else if (collaborationSession.RemoteServiceNames.Contains(anyLspServerProviderName)) { ActiveLanguageServerClient = languageServerGuestService.CreateLanguageServerClient(anyLspServerProviderName); } }; // Register Roslyn supported capabilities languageServerGuestService.RegisterClientMetadata( new string[] { StringConstants.TypeScriptLanguageName }, new LS.LanguageServerClientMetadata( true, JObject.FromObject(new ServerCapabilities { // Uses Roslyn client. DocumentSymbolProvider = true, // Uses LSP SDK client. DocumentLinkProvider = null, RenameProvider = false, DocumentOnTypeFormattingProvider = null, DocumentRangeFormattingProvider = false, DocumentFormattingProvider = false, CodeLensProvider = null, CodeActionProvider = false, ExecuteCommandProvider = null, WorkspaceSymbolProvider = false, DocumentHighlightProvider = false, ReferencesProvider = false, DefinitionProvider = false, SignatureHelpProvider = null, CompletionProvider = null, HoverProvider = false, TextDocumentSync = null, }))); var lifeTimeService = LspClientLifeTimeService; lifeTimeService.Disposed += (s, e) => { ActiveLanguageServerClient?.Dispose(); ActiveLanguageServerClient = null; }; return Task.FromResult<ICollaborationService>(lifeTimeService); } protected abstract class RoslynLSPClientLifeTimeService : ICollaborationService, IDisposable { public event EventHandler Disposed; public void Dispose() => Disposed?.Invoke(this, null); } } [Export] [ExportCollaborationService(typeof(CSharpLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class CSharpLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.CSharpProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new CSharpLSPClientLifeTimeService(); private class CSharpLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } [Export] [ExportCollaborationService(typeof(VisualBasicLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class VisualBasicLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.VisualBasicProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new VisualBasicLSPClientLifeTimeService(); private class VisualBasicLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } [Export] [ExportCollaborationService(typeof(TypeScriptLSPClientLifeTimeService), Scope = SessionScope.Guest, Role = ServiceRole.LocalService, Features = "LspServices", CreationPriority = (int)ServiceRole.LocalService + 2000)] internal class TypeScriptLspClientServiceFactory : AbstractLspClientServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeScriptLspClientServiceFactory() { } protected override string LanguageSpecificProviderName => StringConstants.TypeScriptProviderName; protected override RoslynLSPClientLifeTimeService LspClientLifeTimeService => new TypeScriptLSPClientLifeTimeService(); private class TypeScriptLSPClientLifeTimeService : RoslynLSPClientLifeTimeService { } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/CommandLine/CommandLineReference.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 { /// <summary> /// Describes a command line metadata reference (assembly or netmodule) specification. /// </summary> [DebuggerDisplay("{Reference,nq}")] public struct CommandLineReference : IEquatable<CommandLineReference> { private readonly string _reference; private readonly MetadataReferenceProperties _properties; public CommandLineReference(string reference, MetadataReferenceProperties properties) { Debug.Assert(!string.IsNullOrEmpty(reference)); _reference = reference; _properties = properties; } /// <summary> /// Metadata file path or an assembly display name. /// </summary> public string Reference { get { return _reference; } } /// <summary> /// Metadata reference properties. /// </summary> public MetadataReferenceProperties Properties { get { return _properties; } } public override bool Equals(object? obj) { return obj is CommandLineReference && base.Equals((CommandLineReference)obj); } public bool Equals(CommandLineReference other) { return _reference == other._reference && _properties.Equals(other._properties); } public override int GetHashCode() { return Hash.Combine(_reference, _properties.GetHashCode()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a command line metadata reference (assembly or netmodule) specification. /// </summary> [DebuggerDisplay("{Reference,nq}")] public struct CommandLineReference : IEquatable<CommandLineReference> { private readonly string _reference; private readonly MetadataReferenceProperties _properties; public CommandLineReference(string reference, MetadataReferenceProperties properties) { Debug.Assert(!string.IsNullOrEmpty(reference)); _reference = reference; _properties = properties; } /// <summary> /// Metadata file path or an assembly display name. /// </summary> public string Reference { get { return _reference; } } /// <summary> /// Metadata reference properties. /// </summary> public MetadataReferenceProperties Properties { get { return _properties; } } public override bool Equals(object? obj) { return obj is CommandLineReference && base.Equals((CommandLineReference)obj); } public bool Equals(CommandLineReference other) { return _reference == other._reference && _properties.Equals(other._properties); } public override int GetHashCode() { return Hash.Combine(_reference, _properties.GetHashCode()); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Dependencies/Collections/Internal/ICollectionDebugView`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. // 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/ICollectionDebugView.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; namespace Microsoft.CodeAnalysis.Collections.Internal { internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; public ICollectionDebugView(ICollection<T> collection) { _collection = collection ?? throw new ArgumentNullException(nameof(collection)); } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } }
// Licensed to the .NET Foundation under one or more 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/ICollectionDebugView.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; namespace Microsoft.CodeAnalysis.Collections.Internal { internal sealed class ICollectionDebugView<T> { private readonly ICollection<T> _collection; public ICollectionDebugView(ICollection<T> collection) { _collection = collection ?? throw new ArgumentNullException(nameof(collection)); } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var items = new T[_collection.Count]; _collection.CopyTo(items, 0); return items; } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/Core/Def/xlf/VSPackage.de.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="de" original="../VSPackage.resx"> <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="de" original="../VSPackage.resx"> <body /> </file> </xliff>
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/MSBuildTask/InteractiveCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).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. using System.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).ToArray(); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Setup/DevDivVsix/Directory.Build.targets
<!-- Licensed to the .NET Foundation under one or more 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> <Import Project="..\..\..\Directory.Build.targets" /> <Import Project="$(RepositoryEngineeringDir)targets\PackageProject.targets" Condition="'$(TargetFramework)' != ''"/> </Project>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <Import Project="..\..\..\Directory.Build.targets" /> <Import Project="$(RepositoryEngineeringDir)targets\PackageProject.targets" Condition="'$(TargetFramework)' != ''"/> </Project>
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestLib01.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL[L! ~# @@ @,#O@`  H.text  `.rsrc@@@.reloc ` @B`#Ht  *( *( *( *( *BSJB v4.0.30319l@#~#Stringsd#USl#GUID|<#BlobG %3 81lLL "$P A S F [ F c F k F FF F . .( ?<Module>ErrTestLib01.dllANSBCD`1mscorlibSystemObjectTTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib01 7՟H=F| z\V4  TWrapNonExceptionThrowsT#n# `#_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib01.dll(LegalCopyright LOriginalFilenameErrTestLib01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
MZ@ !L!This program cannot be run in DOS mode. $PEL[L! ~# @@ @,#O@`  H.text  `.rsrc@@@.reloc ` @B`#Ht  *( *( *( *( *BSJB v4.0.30319l@#~#Stringsd#USl#GUID|<#BlobG %3 81lLL "$P A S F [ F c F k F FF F . .( ?<Module>ErrTestLib01.dllANSBCD`1mscorlibSystemObjectTTest.ctorSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeErrTestLib01 7՟H=F| z\V4  TWrapNonExceptionThrowsT#n# `#_CorDllMainmscoree.dll% @0HX@\\4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0DInternalNameErrTestLib01.dll(LegalCopyright LOriginalFilenameErrTestLib01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 3
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/Core/Def/Implementation/Interactive/IAbstractResetInteractiveCommand.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.VisualStudio.Services.Interactive { /// <summary> /// An interface that implements the execution of ResetInteractive. /// Implementation is defined separately from command declaration in order /// to avoid the need to load the dll. /// </summary> internal interface IResetInteractiveCommand { void ExecuteResetInteractive(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.VisualStudio.Services.Interactive { /// <summary> /// An interface that implements the execution of ResetInteractive. /// Implementation is defined separately from command declaration in order /// to avoid the need to load the dll. /// </summary> internal interface IResetInteractiveCommand { void ExecuteResetInteractive(); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Dependencies/Collections/Internal/xlf/Strings.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">La taille du tableau de destination ne permet pas de copier tous les éléments de la collection. Vérifiez l'index et la longueur du tableau.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">Impossible d'effectuer le tri, car la méthode IComparer.Compare() retourne des résultats incohérents. Une valeur comparée n'est pas égale à elle-même ou une valeur comparée de manière répétée à une autre valeur donne des résultats différents. IComparer : '{0}'.</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">La capacité de la table de hachage a été dépassée et est devenue négative. Contrôlez le facteur de chargement, la capacité et la taille actuelle de la table.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">La clé spécifiée '{0}' n'est pas présente dans le dictionnaire.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">Le tableau de destination n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau de destination.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">Le tableau source n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau source.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">La limite inférieure du tableau cible doit être égale à zéro.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">Seuls les tableaux unidimensionnels sont pris en charge pour l'action demandée.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">La valeur "{0}" n'est pas de type "{1}" et ne peut pas être utilisée dans cette collection générique.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">L'objet n'est pas un tableau avec le même nombre d'éléments que celui auquel il doit être comparé.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">Le nombre est inférieur à la limite inférieure du tableau dans la première dimension.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">Plus grand que la taille de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">Le compte doit être positif et faire référence à un emplacement de la chaîne/du tableau/de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">L'index était hors limites. Il ne doit pas être négatif et doit être inférieur à la taille de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">L'index doit être dans les limites de la List.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">Nombre non négatif obligatoire.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">La capacité était inférieure à la taille actuelle.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">Un élément avec la même clé a déjà été ajouté. Clé : {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">Le type de tableau cible n'est pas compatible avec le type des éléments de la collection.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">Offset et length étaient hors limites pour ce tableau ou bien le nombre est supérieur au nombre d'éléments de l'index à la fin de la collection source.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="new">Cannot find the old value</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">Les opérations qui changent des collections non concurrentes doivent avoir un accès exclusif. Une mise à jour simultanée a été effectuée sur cette collection et l'a endommagée. L'état de la collection n'est plus correct.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">La collection a été modifiée ; l'opération d'énumération peut ne pas s'exécuter.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">L'énumération n'a pas commencé ou est déjà terminée.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">Impossible de comparer deux éléments dans le tableau.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">La collection était d'une taille fixe.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">La mutation d'une collection de clés dérivée d'un dictionnaire n'est pas autorisée.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">La mutation d'une collection de valeurs dérivée d'un dictionnaire n'est pas autorisée.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</source> <target state="translated">Les tableaux spécifiés doivent avoir le même nombre de dimensions.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">La taille du tableau de destination ne permet pas de copier tous les éléments de la collection. Vérifiez l'index et la longueur du tableau.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">Impossible d'effectuer le tri, car la méthode IComparer.Compare() retourne des résultats incohérents. Une valeur comparée n'est pas égale à elle-même ou une valeur comparée de manière répétée à une autre valeur donne des résultats différents. IComparer : '{0}'.</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">La capacité de la table de hachage a été dépassée et est devenue négative. Contrôlez le facteur de chargement, la capacité et la taille actuelle de la table.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">La clé spécifiée '{0}' n'est pas présente dans le dictionnaire.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">Le tableau de destination n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau de destination.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">Le tableau source n'est pas assez long. Vérifiez l'index, la longueur ainsi que les limites inférieures du tableau source.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">La limite inférieure du tableau cible doit être égale à zéro.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">Seuls les tableaux unidimensionnels sont pris en charge pour l'action demandée.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">La valeur "{0}" n'est pas de type "{1}" et ne peut pas être utilisée dans cette collection générique.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">L'objet n'est pas un tableau avec le même nombre d'éléments que celui auquel il doit être comparé.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">Le nombre est inférieur à la limite inférieure du tableau dans la première dimension.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">Plus grand que la taille de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">Le compte doit être positif et faire référence à un emplacement de la chaîne/du tableau/de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">L'index était hors limites. Il ne doit pas être négatif et doit être inférieur à la taille de la collection.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">L'index doit être dans les limites de la List.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">Nombre non négatif obligatoire.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">La capacité était inférieure à la taille actuelle.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">Un élément avec la même clé a déjà été ajouté. Clé : {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">Le type de tableau cible n'est pas compatible avec le type des éléments de la collection.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">Offset et length étaient hors limites pour ce tableau ou bien le nombre est supérieur au nombre d'éléments de l'index à la fin de la collection source.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="new">Cannot find the old value</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">Les opérations qui changent des collections non concurrentes doivent avoir un accès exclusif. Une mise à jour simultanée a été effectuée sur cette collection et l'a endommagée. L'état de la collection n'est plus correct.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">La collection a été modifiée ; l'opération d'énumération peut ne pas s'exécuter.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">L'énumération n'a pas commencé ou est déjà terminée.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">Impossible de comparer deux éléments dans le tableau.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">La collection était d'une taille fixe.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">La mutation d'une collection de clés dérivée d'un dictionnaire n'est pas autorisée.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">La mutation d'une collection de valeurs dérivée d'un dictionnaire n'est pas autorisée.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</source> <target state="translated">Les tableaux spécifiés doivent avoir le même nombre de dimensions.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/IntegrationTest/TestUtilities/WellKnownTagNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public class WellKnownTagNames { public const string MarkerFormatDefinition_HighlightedReference = "MarkerFormatDefinition/HighlightedReference"; public const string MarkerFormatDefinition_HighlightedDefinition = "MarkerFormatDefinition/HighlightedDefinition"; public const string MarkerFormatDefinition_HighlightedWrittenReference = "MarkerFormatDefinition/HighlightedWrittenReference"; public static Type? GetTagTypeByName(string typeName) { switch (typeName) { case MarkerFormatDefinition_HighlightedReference: return typeof(ReferenceHighlightTag); case MarkerFormatDefinition_HighlightedDefinition: return typeof(DefinitionHighlightTag); case MarkerFormatDefinition_HighlightedWrittenReference: return typeof(WrittenReferenceHighlightTag); default: return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public class WellKnownTagNames { public const string MarkerFormatDefinition_HighlightedReference = "MarkerFormatDefinition/HighlightedReference"; public const string MarkerFormatDefinition_HighlightedDefinition = "MarkerFormatDefinition/HighlightedDefinition"; public const string MarkerFormatDefinition_HighlightedWrittenReference = "MarkerFormatDefinition/HighlightedWrittenReference"; public static Type? GetTagTypeByName(string typeName) { switch (typeName) { case MarkerFormatDefinition_HighlightedReference: return typeof(ReferenceHighlightTag); case MarkerFormatDefinition_HighlightedDefinition: return typeof(DefinitionHighlightTag); case MarkerFormatDefinition_HighlightedWrittenReference: return typeof(WrittenReferenceHighlightTag); default: return null; } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/IFSharpLanguageDebugInfoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal interface IFSharpLanguageDebugInfoService { Task<FSharpDebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken); /// <summary> /// Find an appropriate span to pass the debugger given a point in a snapshot. Optionally /// pass back a string to pass to the debugger instead if no good span can be found. For /// example, if the user hovers on "var" then we actually want to pass the fully qualified /// name of the type that 'var' binds to, to the debugger. /// </summary> Task<FSharpDebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal interface IFSharpLanguageDebugInfoService { Task<FSharpDebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken); /// <summary> /// Find an appropriate span to pass the debugger given a point in a snapshot. Optionally /// pass back a string to pass to the debugger instead if no good span can be found. For /// example, if the user hovers on "var" then we actually want to pass the fully qualified /// name of the type that 'var' binds to, to the debugger. /// </summary> Task<FSharpDebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.it.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="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</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="it" original="../CSharpCompilerExtensionsResources.resx"> <body> <trans-unit id="Code_block_preferences"> <source>Code-block preferences</source> <target state="translated">Preferenze per blocchi di codice</target> <note /> </trans-unit> <trans-unit id="Expected_string_or_char_literal"> <source>Expected string or char literal</source> <target state="translated">È previsto un valore letterale di tipo stringa o char</target> <note /> </trans-unit> <trans-unit id="Expression_bodied_members"> <source>Expression-bodied members</source> <target state="translated">Membri con corpo di espressione</target> <note /> </trans-unit> <trans-unit id="Null_checking_preferences"> <source>Null-checking preferences</source> <target state="translated">Preference per controllo valori Null</target> <note /> </trans-unit> <trans-unit id="Pattern_matching_preferences"> <source>Pattern matching preferences</source> <target state="translated">Preferenze per criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="_0_1_is_not_supported_in_this_version"> <source>'{0}.{1}' is not supported in this version</source> <target state="translated">'{0}.{1}' non è supportato in questa versione</target> <note>{0}: A type name {1}: A member name</note> </trans-unit> <trans-unit id="using_directive_preferences"> <source>'using' directive preferences</source> <target state="translated">Preferenze per direttive 'using'</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="var_preferences"> <source>var preferences</source> <target state="translated">Preferenze per var</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/UsingBlockHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class UsingBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(UsingBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestUsingBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|Using|]|} f = File.Open(name) Read(f) [|End Using|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestUsingBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|Using|] f = File.Open(name) Read(f) {|Cursor:[|End Using|]|} End Sub End Class</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class UsingBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(UsingBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestUsingBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|Using|]|} f = File.Open(name) Read(f) [|End Using|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestUsingBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|Using|] f = File.Open(name) Read(f) {|Cursor:[|End Using|]|} End Sub End Class</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/TestUtilities/Threading/WpfTestRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { /// <summary> /// This type is actually responsible for spinning up the STA context to run all of the /// tests. /// /// Overriding the <see cref="XunitTestInvoker"/> to setup the STA context is not the correct /// approach. That type begins constructing types before RunAsync and hence ctors end up /// running on the current thread vs. the STA ones. Just completely wrapping the invocation /// here is the best case. /// </summary> public sealed class WpfTestRunner : XunitTestRunner { private static readonly ImmutableDictionary<string, TestInfo> _passedTests; private static string s_wpfFactRequirementReason; public WpfTestSharedData SharedData { get; } static WpfTestRunner() => _passedTests = TestInfo.GetPassedTestsInfo(); public WpfTestRunner( WpfTestSharedData sharedData, ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override Task<decimal> InvokeTestMethodAsync(ExceptionAggregator aggregator) { SharedData.ExecutingTest(TestMethod); var sta = StaTaskScheduler.DefaultSta; var task = Task.Factory.StartNew(async () => { Debug.Assert(sta.StaThread == Thread.CurrentThread); using (await SharedData.TestSerializationGate.DisposableWaitAsync(CancellationToken.None)) { try { Debug.Assert(SynchronizationContext.Current is DispatcherSynchronizationContext); // Reset our flag ensuring that part of this test actually needs WpfFact s_wpfFactRequirementReason = null; if (_passedTests.TryGetValue(Test.DisplayName, out var info)) { return info.Time; } else { // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context. var invoker = new XunitTestInvoker(Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments, BeforeAfterAttributes, aggregator, CancellationTokenSource); return invoker.RunAsync().JoinUsingDispatcher(CancellationTokenSource.Token); } } finally { // Cleanup the synchronization context even if the test is failing exceptionally SynchronizationContext.SetSynchronizationContext(null); } } }, CancellationTokenSource.Token, TaskCreationOptions.None, new SynchronizationContextTaskScheduler(sta.DispatcherSynchronizationContext)); return task.Unwrap(); } /// <summary> /// Asserts that the test is running on a <see cref="WpfFactAttribute"/> or <see cref="WpfTheoryAttribute"/> /// test method, and records the reason for requiring the use of an STA thread. /// </summary> internal static void RequireWpfFact(string reason) { if (!(TestExportJoinableTaskContext.GetEffectiveSynchronizationContext() is DispatcherSynchronizationContext)) { throw new InvalidOperationException($"This test requires {nameof(WpfFactAttribute)} because '{reason}' but is missing {nameof(WpfFactAttribute)}. Either the attribute should be changed, or the reason it needs an STA thread audited."); } s_wpfFactRequirementReason = reason; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { /// <summary> /// This type is actually responsible for spinning up the STA context to run all of the /// tests. /// /// Overriding the <see cref="XunitTestInvoker"/> to setup the STA context is not the correct /// approach. That type begins constructing types before RunAsync and hence ctors end up /// running on the current thread vs. the STA ones. Just completely wrapping the invocation /// here is the best case. /// </summary> public sealed class WpfTestRunner : XunitTestRunner { private static readonly ImmutableDictionary<string, TestInfo> _passedTests; private static string s_wpfFactRequirementReason; public WpfTestSharedData SharedData { get; } static WpfTestRunner() => _passedTests = TestInfo.GetPassedTestsInfo(); public WpfTestRunner( WpfTestSharedData sharedData, ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override Task<decimal> InvokeTestMethodAsync(ExceptionAggregator aggregator) { SharedData.ExecutingTest(TestMethod); var sta = StaTaskScheduler.DefaultSta; var task = Task.Factory.StartNew(async () => { Debug.Assert(sta.StaThread == Thread.CurrentThread); using (await SharedData.TestSerializationGate.DisposableWaitAsync(CancellationToken.None)) { try { Debug.Assert(SynchronizationContext.Current is DispatcherSynchronizationContext); // Reset our flag ensuring that part of this test actually needs WpfFact s_wpfFactRequirementReason = null; if (_passedTests.TryGetValue(Test.DisplayName, out var info)) { return info.Time; } else { // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context. var invoker = new XunitTestInvoker(Test, MessageBus, TestClass, ConstructorArguments, TestMethod, TestMethodArguments, BeforeAfterAttributes, aggregator, CancellationTokenSource); return invoker.RunAsync().JoinUsingDispatcher(CancellationTokenSource.Token); } } finally { // Cleanup the synchronization context even if the test is failing exceptionally SynchronizationContext.SetSynchronizationContext(null); } } }, CancellationTokenSource.Token, TaskCreationOptions.None, new SynchronizationContextTaskScheduler(sta.DispatcherSynchronizationContext)); return task.Unwrap(); } /// <summary> /// Asserts that the test is running on a <see cref="WpfFactAttribute"/> or <see cref="WpfTheoryAttribute"/> /// test method, and records the reason for requiring the use of an STA thread. /// </summary> internal static void RequireWpfFact(string reason) { if (!(TestExportJoinableTaskContext.GetEffectiveSynchronizationContext() is DispatcherSynchronizationContext)) { throw new InvalidOperationException($"This test requires {nameof(WpfFactAttribute)} because '{reason}' but is missing {nameof(WpfFactAttribute)}. Either the attribute should be changed, or the reason it needs an STA thread audited."); } s_wpfFactRequirementReason = reason; } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag1() { const string code = @" {|span:/// $$XML doc comment /// some description /// of /// the comment|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// XML doc comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag2() { const string code = @" {|span:/** $$Block comment * some description * of * the comment */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** Block comment ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithoutSummaryTag3() { const string code = @" {|span:/// $$<param name=""tree""></param>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentWithLongBannerText() { var code = @" {|span:/// $$<summary> /// " + new string('x', 240) + @" /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationComment() { const string code = @" {|span:/// <summary> /// $$Hello C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationComment() { const string code = @" {|span:/** <summary> $$Hello C#! </summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedDocumentationCommentOnASingleLine() { const string code = @" {|span:/// <summary>$$Hello C#!</summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestIndentedMultilineDocumentationCommentOnASingleLine() { const string code = @" {|span:/** <summary>$$Hello C#!</summary> */|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/** <summary>Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment1() { const string code = @" {|span:/// <summary> /// $$Hello /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestMultilineSummaryInDocumentationComment2() { const string code = @" {|span:/// <summary> /// $$Hello /// /// C#! /// </summary>|} class Class3 { }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Hello C#!", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] [WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")] public async Task CrefInSummary() { const string code = @" class C { {|span:/// $$<summary> /// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />, /// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />. /// </summary>|} public void M<T>(T t) { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true)); } [WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithPunctuation() { const string code = @" class C { {|span:/// $$<summary> /// The main entrypoint for <see cref=""Program""/>. /// </summary> /// <param name=""args""></param>|} void Main() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true)); } [WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")] [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestSummaryWithAdditionalTags() { const string code = @" public class Class1 { {|span:/// $$<summary> /// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class. /// </summary>|} public Class1() { } }"; await VerifyBlockSpansAsync(code, Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true)); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/VisualBasic/Portable/Declarations/DeclarationTable.Cache.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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class DeclarationTable ' The structure of the DeclarationTable provides us with a set of 'old' declarations that ' stay relatively unchanged and a 'new' declaration that is repeatedly added and removed. ' This mimics the expected usage pattern of a user repeatedly typing in a single file. ' Because of this usage pattern, we can cache information about these 'old' declarations and ' keep that around as long as they do not change. For example, we keep a single 'merged ' declaration' for all those root declarations as well as sets of interesting information ' (like the type names in those decls). Private Class Cache ' The merged root declaration for all the 'old' declarations. Friend ReadOnly MergedRoot As Lazy(Of MergedNamespaceDeclaration) ' All the simple type names for all the types in the 'old' declarations. Friend ReadOnly TypeNames As Lazy(Of ICollection(Of String)) Friend ReadOnly NamespaceNames As Lazy(Of ICollection(Of String)) Friend ReadOnly ReferenceDirectives As Lazy(Of ImmutableArray(Of ReferenceDirective)) Public Sub New(table As DeclarationTable) Me.MergedRoot = New Lazy(Of MergedNamespaceDeclaration)(AddressOf table.MergeOlderNamespaces) Me.TypeNames = New Lazy(Of ICollection(Of String))(Function() GetTypeNames(Me.MergedRoot.Value)) Me.NamespaceNames = New Lazy(Of ICollection(Of String))(Function() GetNamespaceNames(Me.MergedRoot.Value)) Me.ReferenceDirectives = New Lazy(Of ImmutableArray(Of ReferenceDirective))( Function() table.SelectManyFromOlderDeclarationsNoEmbedded(Function(r) r.ReferenceDirectives)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/Core/Portable/Collections/IdentifierCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// A dictionary that maps strings to all known spellings of that string. Can be used to /// efficiently store the set of known type names for a module for both VB and C# while also /// answering questions like "do you have a type called Goo" in either a case sensitive or /// insensitive manner. /// </summary> internal partial class IdentifierCollection { // Maps an identifier to all spellings of that identifier in this module. The value type is // typed as object so that it can store either an individual element (the common case), or a // collection. // // Note: we use a case insensitive comparer so that we can quickly lookup if we know a name // regardless of its case. private readonly Dictionary<string, object> _map = new Dictionary<string, object>( StringComparer.OrdinalIgnoreCase); public IdentifierCollection() { } public IdentifierCollection(IEnumerable<string> identifiers) { this.AddIdentifiers(identifiers); } public void AddIdentifiers(IEnumerable<string> identifiers) { foreach (var identifier in identifiers) { AddIdentifier(identifier); } } public void AddIdentifier(string identifier) { RoslynDebug.Assert(identifier != null); object? value; if (!_map.TryGetValue(identifier, out value)) { AddInitialSpelling(identifier); } else { AddAdditionalSpelling(identifier, value); } } private void AddAdditionalSpelling(string identifier, object value) { // Had a mapping for it. It will either map to a single // spelling, or to a set of spellings. var strValue = value as string; if (strValue != null) { if (!string.Equals(identifier, strValue, StringComparison.Ordinal)) { // We now have two spellings. Create a collection for // that and map the name to it. _map[identifier] = new HashSet<string> { identifier, strValue }; } } else { // We have multiple spellings already. var spellings = (HashSet<string>)value; // Note: the set will prevent duplicates. spellings.Add(identifier); } } private void AddInitialSpelling(string identifier) { // We didn't have any spellings for this word already. Just // add the word as the single known spelling. _map.Add(identifier, identifier); } public bool ContainsIdentifier(string identifier, bool caseSensitive) { RoslynDebug.Assert(identifier != null); if (caseSensitive) { return CaseSensitiveContains(identifier); } else { return CaseInsensitiveContains(identifier); } } private bool CaseInsensitiveContains(string identifier) { // Simple case. Just check if we've mapped this word to // anything. The map will take care of the case insensitive // lookup for us. return _map.ContainsKey(identifier); } private bool CaseSensitiveContains(string identifier) { object? spellings; if (_map.TryGetValue(identifier, out spellings)) { var spelling = spellings as string; if (spelling != null) { return string.Equals(identifier, spelling, StringComparison.Ordinal); } var set = (HashSet<string>)spellings; return set.Contains(identifier); } return false; } public ICollection<string> AsCaseSensitiveCollection() { return new CaseSensitiveCollection(this); } public ICollection<string> AsCaseInsensitiveCollection() { return new CaseInsensitiveCollection(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// A dictionary that maps strings to all known spellings of that string. Can be used to /// efficiently store the set of known type names for a module for both VB and C# while also /// answering questions like "do you have a type called Goo" in either a case sensitive or /// insensitive manner. /// </summary> internal partial class IdentifierCollection { // Maps an identifier to all spellings of that identifier in this module. The value type is // typed as object so that it can store either an individual element (the common case), or a // collection. // // Note: we use a case insensitive comparer so that we can quickly lookup if we know a name // regardless of its case. private readonly Dictionary<string, object> _map = new Dictionary<string, object>( StringComparer.OrdinalIgnoreCase); public IdentifierCollection() { } public IdentifierCollection(IEnumerable<string> identifiers) { this.AddIdentifiers(identifiers); } public void AddIdentifiers(IEnumerable<string> identifiers) { foreach (var identifier in identifiers) { AddIdentifier(identifier); } } public void AddIdentifier(string identifier) { RoslynDebug.Assert(identifier != null); object? value; if (!_map.TryGetValue(identifier, out value)) { AddInitialSpelling(identifier); } else { AddAdditionalSpelling(identifier, value); } } private void AddAdditionalSpelling(string identifier, object value) { // Had a mapping for it. It will either map to a single // spelling, or to a set of spellings. var strValue = value as string; if (strValue != null) { if (!string.Equals(identifier, strValue, StringComparison.Ordinal)) { // We now have two spellings. Create a collection for // that and map the name to it. _map[identifier] = new HashSet<string> { identifier, strValue }; } } else { // We have multiple spellings already. var spellings = (HashSet<string>)value; // Note: the set will prevent duplicates. spellings.Add(identifier); } } private void AddInitialSpelling(string identifier) { // We didn't have any spellings for this word already. Just // add the word as the single known spelling. _map.Add(identifier, identifier); } public bool ContainsIdentifier(string identifier, bool caseSensitive) { RoslynDebug.Assert(identifier != null); if (caseSensitive) { return CaseSensitiveContains(identifier); } else { return CaseInsensitiveContains(identifier); } } private bool CaseInsensitiveContains(string identifier) { // Simple case. Just check if we've mapped this word to // anything. The map will take care of the case insensitive // lookup for us. return _map.ContainsKey(identifier); } private bool CaseSensitiveContains(string identifier) { object? spellings; if (_map.TryGetValue(identifier, out spellings)) { var spelling = spellings as string; if (spelling != null) { return string.Equals(identifier, spelling, StringComparison.Ordinal); } var set = (HashSet<string>)spellings; return set.Contains(identifier); } return false; } public ICollection<string> AsCaseSensitiveCollection() { return new CaseSensitiveCollection(this); } public ICollection<string> AsCaseInsensitiveCollection() { return new CaseInsensitiveCollection(this); } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/VisualStudio/Core/Def/Implementation/Progression/IconHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
-1
dotnet/roslyn
55,715
Don't consider syntax trees changed if the compilation is the same
We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
chsienki
2021-08-19T00:01:24Z
2021-08-26T21:56:19Z
ab091e60797b24c607601eff9029f53071e7ab93
afb221532f76e065cdf969cab5ad5d849810407c
Don't consider syntax trees changed if the compilation is the same. We can skip looking at syntax trees completely when the compilation is the same as one we've seen before. When all the syntax nodes successfully ran the previous iteration (i.e. no exceptions, no new generators have been added) we can just use their cached values directly.
./src/Compilers/CSharp/Test/Symbol/Compilation/IndexedProperties_BindingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IndexedProperties_BindingTests : SemanticModelTestBase { [ClrOnlyFact] public void OldGetFormat_IndexedProperties() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = /*<bind>*/a.get_P1/*</bind>*/(1); } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Method, "get_P1"); } [ClrOnlyFact] public void IndexedProperties_Complete() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = a./*<bind>*/P1/*</bind>*/[3]++; } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_Incomplete() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = /*<bind>*/a.P1/*</bind>*/[3 } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_Set_In_Constructor() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(){/*<bind>*/P1/*</bind>*/ = 2}; } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_LINQ() { var reference = GetReference(); var source = @" using System; using System.Linq; class B { static void Main(string[] args) { IA a; a = new IA(); int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var query = from val in arr where val > /*<bind>*/a.P1/*</bind>*/[2] select val; foreach (var val in query) Console.WriteLine(val); } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } private void IndexedPropertiesBindingChecks(string source, MetadataReference reference, SymbolKind symbolKind, string name) { var tree = Parse(source); var comp = CreateCompilation(tree, new[] { reference }); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(symbolKind, sym.Symbol.Kind); Assert.Equal(name, sym.Symbol.Name); var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, typeInfo); var methodGroup = model.GetMemberGroup(expr); Assert.NotEqual(default, methodGroup); var indexerGroup = model.GetIndexerGroup(expr); Assert.NotEqual(default, indexerGroup); var position = GetPositionForBinding(tree); // Get the list of LookupNames at the location at the end of the tag var actual_lookupNames = model.LookupNames(position); Assert.NotEmpty(actual_lookupNames); Assert.True(actual_lookupNames.Contains("System"), "LookupNames does not contain System"); Assert.True(actual_lookupNames.Contains("Main"), "LookupNames does not contain Main"); Assert.True(actual_lookupNames.Contains("IA"), "LookupNames does not contain IA"); Assert.True(actual_lookupNames.Contains("A"), "LookupNames does not contain A"); Assert.True(actual_lookupNames.Contains("a"), "LookupNames does not contain a"); // Get the list of LookupSymbols at the location at the end of the tag var actual_lookupSymbols = model.LookupSymbols(position); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupSymbols_as_string); Assert.True(actual_lookupSymbols_as_string.Contains("void B.Main(System.String[] args)"), "LookupSymbols does not contain Main"); Assert.True(actual_lookupSymbols_as_string.Contains("System"), "LookupSymbols does not contain System"); Assert.True(actual_lookupSymbols_as_string.Contains("IA"), "LookupSymbols does not contain IA"); Assert.True(actual_lookupSymbols_as_string.Contains("A"), "LookupSymbols does not contain A"); } private static MetadataReference GetReference() { var COMSource = @" Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> <CoClass(GetType(A))> Public Interface IA Property P1(Optional index As Integer = 1) As Integer End Interface Public Class A Implements IA Property P1(Optional index As Integer = 1) As Integer Implements IA.P1 Get Return 1 End Get Set End Set End Property End Class "; var reference = BasicCompilationUtils.CompileToMetadata(COMSource, verify: Verification.Passes); return reference; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IndexedProperties_BindingTests : SemanticModelTestBase { [ClrOnlyFact] public void OldGetFormat_IndexedProperties() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = /*<bind>*/a.get_P1/*</bind>*/(1); } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Method, "get_P1"); } [ClrOnlyFact] public void IndexedProperties_Complete() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = a./*<bind>*/P1/*</bind>*/[3]++; } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_Incomplete() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(); int ret = /*<bind>*/a.P1/*</bind>*/[3 } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_Set_In_Constructor() { var reference = GetReference(); var source = @" using System; class B { static void Main(string[] args) { IA a; a = new IA(){/*<bind>*/P1/*</bind>*/ = 2}; } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } [ClrOnlyFact] public void IndexedProperties_LINQ() { var reference = GetReference(); var source = @" using System; using System.Linq; class B { static void Main(string[] args) { IA a; a = new IA(); int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var query = from val in arr where val > /*<bind>*/a.P1/*</bind>*/[2] select val; foreach (var val in query) Console.WriteLine(val); } } "; IndexedPropertiesBindingChecks(source, reference, SymbolKind.Property, "P1"); } private void IndexedPropertiesBindingChecks(string source, MetadataReference reference, SymbolKind symbolKind, string name) { var tree = Parse(source); var comp = CreateCompilation(tree, new[] { reference }); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var sym = model.GetSymbolInfo(expr); Assert.Equal(symbolKind, sym.Symbol.Kind); Assert.Equal(name, sym.Symbol.Name); var typeInfo = model.GetTypeInfo(expr); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, typeInfo); var methodGroup = model.GetMemberGroup(expr); Assert.NotEqual(default, methodGroup); var indexerGroup = model.GetIndexerGroup(expr); Assert.NotEqual(default, indexerGroup); var position = GetPositionForBinding(tree); // Get the list of LookupNames at the location at the end of the tag var actual_lookupNames = model.LookupNames(position); Assert.NotEmpty(actual_lookupNames); Assert.True(actual_lookupNames.Contains("System"), "LookupNames does not contain System"); Assert.True(actual_lookupNames.Contains("Main"), "LookupNames does not contain Main"); Assert.True(actual_lookupNames.Contains("IA"), "LookupNames does not contain IA"); Assert.True(actual_lookupNames.Contains("A"), "LookupNames does not contain A"); Assert.True(actual_lookupNames.Contains("a"), "LookupNames does not contain a"); // Get the list of LookupSymbols at the location at the end of the tag var actual_lookupSymbols = model.LookupSymbols(position); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupSymbols_as_string); Assert.True(actual_lookupSymbols_as_string.Contains("void B.Main(System.String[] args)"), "LookupSymbols does not contain Main"); Assert.True(actual_lookupSymbols_as_string.Contains("System"), "LookupSymbols does not contain System"); Assert.True(actual_lookupSymbols_as_string.Contains("IA"), "LookupSymbols does not contain IA"); Assert.True(actual_lookupSymbols_as_string.Contains("A"), "LookupSymbols does not contain A"); } private static MetadataReference GetReference() { var COMSource = @" Imports System Imports System.Collections.Generic Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> <CoClass(GetType(A))> Public Interface IA Property P1(Optional index As Integer = 1) As Integer End Interface Public Class A Implements IA Property P1(Optional index As Integer = 1) As Integer Implements IA.P1 Get Return 1 End Get Set End Set End Property End Class "; var reference = BasicCompilationUtils.CompileToMetadata(COMSource, verify: Verification.Passes); return reference; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Analyzers/CSharp/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddAccessibilityModifiers { using VerifyCS = CSharpCodeFixVerifier< CSharpAddAccessibilityModifiersDiagnosticAnalyzer, CSharpAddAccessibilityModifiersCodeFixProvider>; public class AddAccessibilityModifiersTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAllConstructs() { await VerifyCS.VerifyCodeFixAsync( @"using System; namespace Outer { namespace Inner1.Inner2 { partial class [|C|] : I { class [|NestedClass|] { } struct [|NestedStruct|] { } int [|f1|]; int [|f2|], f3; public int f4; event Action [|e1|], e2; public event Action e3; event Action [|e4|] { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } [|C|]() { } public C(int i) { } ~C() { } void [|M1|]() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } int [|P1|] { get; } public int P2 { get; } int I.P3 { get; } int [|this|][int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } interface [|I|] { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } delegate void [|D|](); enum [|E|] { EMember } } }", @"using System; namespace Outer { namespace Inner1.Inner2 { internal partial class C : I { private class NestedClass { } private struct NestedStruct { } private int f1; private int f2, f3; public int f4; private event Action e1, e2; public event Action e3; private event Action e4 { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } private C() { } public C(int i) { } ~C() { } private void M1() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } private int P1 { get; } public int P2 { get; } int I.P3 { get; } private int this[int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } internal interface I { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } internal delegate void D(); internal enum E { EMember } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRefStructs() { await VerifyCS.VerifyCodeFixAsync(@" namespace Test { ref struct [|S1|] { } }", @" namespace Test { internal ref struct S1 { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRecords() { var source = @" record [|Record|] { int [|field|]; } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }"; var fixedSource = @" internal record Record { private int field; } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }"; var test = new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }; await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRecordStructs() { var source = @" record struct [|Record|] { int [|field|]; } "; var fixedSource = @" internal record struct Record { private int field; } "; var test = new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.Preview, }; await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestReadOnlyStructs() { await VerifyCS.VerifyCodeFixAsync(@" namespace Test { readonly struct [|S1|] { } }", @" namespace Test { internal readonly struct S1 { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAllConstructsWithOmit() { await new VerifyCS.Test { TestState = { Sources = { @"using System; namespace Outer { namespace Inner1.Inner2 { internal partial class [|C|] : I { private class [|NestedClass|] { } private struct [|NestedStruct|] { } private int [|f1|]; private int [|f2|], f3; public int f4; private event Action [|e1|], e2; public event Action e3; private event Action [|e4|] { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } private [|C|]() { } public C(int i) { } ~C() { } private void [|M1|]() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } private int [|P1|] { get; } public int P2 { get; } int I.P3 { get; } private int [|this|][int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } internal interface [|I|] { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } internal delegate void [|D|](); internal enum [|E|] { EMember } } }", }, }, FixedState = { Sources = { @"using System; namespace Outer { namespace Inner1.Inner2 { partial class C : I { class NestedClass { } struct NestedStruct { } int f1; int f2, f3; public int f4; event Action e1, e2; public event Action e3; event Action e4 { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } C() { } public C(int i) { } ~C() { } void M1() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } int P1 { get; } public int P2 { get; } int I.P3 { get; } int this[int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } interface I { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } delegate void D(); enum E { EMember } } }", }, }, Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRefStructsWithOmit() { await new VerifyCS.Test { TestCode = @" namespace Test { internal ref struct [|S1|] { } }", FixedCode = @" namespace Test { ref struct S1 { } }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestReadOnlyStructsWithOmit() { await new VerifyCS.Test { TestCode = @" namespace Test { internal readonly struct [|S1|] { } }", FixedCode = @" namespace Test { readonly struct S1 { } }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestClassOutsideNamespace() { await new VerifyCS.Test { TestCode = @" internal class [|C1|] { }", FixedCode = @" class C1 { }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestExternMethod() { await VerifyCS.VerifyCodeFixAsync(@" using System; using System.Runtime.InteropServices; internal class Program { [DllImport(""User32.dll"", CharSet = CharSet.Unicode)] static extern int [|MessageBox|](IntPtr h, string m, string c, int type); } ", @" using System; using System.Runtime.InteropServices; internal class Program { [DllImport(""User32.dll"", CharSet = CharSet.Unicode)] private static extern int [|MessageBox|](IntPtr h, string m, string c, int type); } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestVolatile() { await VerifyCS.VerifyCodeFixAsync(@" internal class Program { volatile int [|x|]; } ", @" internal class Program { private volatile int x; } "); } [WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAbstractMethod() { await VerifyCS.VerifyCodeFixAsync(@" public abstract class TestClass { abstract string {|CS0621:[|Test|]|} { get; } } ", @" public abstract class TestClass { protected abstract string Test { get; } } "); } [WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestOverriddenMethod() { await VerifyCS.VerifyCodeFixAsync(@" public abstract class TestClass { public abstract string Test { get; } } public class Derived : TestClass { override string {|CS0507:{|CS0621:[|Test|]|}|} { get; } } ", @" public abstract class TestClass { public abstract string Test { get; } } public class Derived : TestClass { public override string Test { get; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestFileScopedNamespaces() { await new VerifyCS.Test { TestCode = @" namespace Test; struct [|S1|] { } ", FixedCode = @" namespace Test; internal struct S1 { } ", LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddAccessibilityModifiers { using VerifyCS = CSharpCodeFixVerifier< CSharpAddAccessibilityModifiersDiagnosticAnalyzer, CSharpAddAccessibilityModifiersCodeFixProvider>; public class AddAccessibilityModifiersTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAllConstructs() { await VerifyCS.VerifyCodeFixAsync( @"using System; namespace Outer { namespace Inner1.Inner2 { partial class [|C|] : I { class [|NestedClass|] { } struct [|NestedStruct|] { } int [|f1|]; int [|f2|], f3; public int f4; event Action [|e1|], e2; public event Action e3; event Action [|e4|] { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } [|C|]() { } public C(int i) { } ~C() { } void [|M1|]() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } int [|P1|] { get; } public int P2 { get; } int I.P3 { get; } int [|this|][int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } interface [|I|] { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } delegate void [|D|](); enum [|E|] { EMember } } }", @"using System; namespace Outer { namespace Inner1.Inner2 { internal partial class C : I { private class NestedClass { } private struct NestedStruct { } private int f1; private int f2, f3; public int f4; private event Action e1, e2; public event Action e3; private event Action e4 { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } private C() { } public C(int i) { } ~C() { } private void M1() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } private int P1 { get; } public int P2 { get; } int I.P3 { get; } private int this[int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } internal interface I { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } internal delegate void D(); internal enum E { EMember } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRefStructs() { await VerifyCS.VerifyCodeFixAsync(@" namespace Test { ref struct [|S1|] { } }", @" namespace Test { internal ref struct S1 { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRecords() { var source = @" record [|Record|] { int [|field|]; } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }"; var fixedSource = @" internal record Record { private int field; } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }"; var test = new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9, }; await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRecordStructs() { var source = @" record struct [|Record|] { int [|field|]; } "; var fixedSource = @" internal record struct Record { private int field; } "; var test = new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.Preview, }; await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestReadOnlyStructs() { await VerifyCS.VerifyCodeFixAsync(@" namespace Test { readonly struct [|S1|] { } }", @" namespace Test { internal readonly struct S1 { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAllConstructsWithOmit() { await new VerifyCS.Test { TestState = { Sources = { @"using System; namespace Outer { namespace Inner1.Inner2 { internal partial class [|C|] : I { private class [|NestedClass|] { } private struct [|NestedStruct|] { } private int [|f1|]; private int [|f2|], f3; public int f4; private event Action [|e1|], e2; public event Action e3; private event Action [|e4|] { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } private [|C|]() { } public C(int i) { } ~C() { } private void [|M1|]() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } private int [|P1|] { get; } public int P2 { get; } int I.P3 { get; } private int [|this|][int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } internal interface [|I|] { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } internal delegate void [|D|](); internal enum [|E|] { EMember } } }", }, }, FixedState = { Sources = { @"using System; namespace Outer { namespace Inner1.Inner2 { partial class C : I { class NestedClass { } struct NestedStruct { } int f1; int f2, f3; public int f4; event Action e1, e2; public event Action e3; event Action e4 { add { } remove { } } public event Action e5 { add { } remove { } } event Action I.e6 { add { } remove { } } static C() { } C() { } public C(int i) { } ~C() { } void M1() { } public void M2() { } void I.M3() { } partial void M4(); partial void M4() { } int P1 { get; } public int P2 { get; } int I.P3 { get; } int this[int i] => throw null; public int this[string s] => throw null; int I.this[bool b] => throw null; } interface I { event Action e6; void M3(); int P3 { get; } int this[bool b] { get; } } delegate void D(); enum E { EMember } } }", }, }, Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestRefStructsWithOmit() { await new VerifyCS.Test { TestCode = @" namespace Test { internal ref struct [|S1|] { } }", FixedCode = @" namespace Test { ref struct S1 { } }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestReadOnlyStructsWithOmit() { await new VerifyCS.Test { TestCode = @" namespace Test { internal readonly struct [|S1|] { } }", FixedCode = @" namespace Test { readonly struct S1 { } }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestClassOutsideNamespace() { await new VerifyCS.Test { TestCode = @" internal class [|C1|] { }", FixedCode = @" class C1 { }", Options = { { CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestExternMethod() { await VerifyCS.VerifyCodeFixAsync(@" using System; using System.Runtime.InteropServices; internal class Program { [DllImport(""User32.dll"", CharSet = CharSet.Unicode)] static extern int [|MessageBox|](IntPtr h, string m, string c, int type); } ", @" using System; using System.Runtime.InteropServices; internal class Program { [DllImport(""User32.dll"", CharSet = CharSet.Unicode)] private static extern int [|MessageBox|](IntPtr h, string m, string c, int type); } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestVolatile() { await VerifyCS.VerifyCodeFixAsync(@" internal class Program { volatile int [|x|]; } ", @" internal class Program { private volatile int x; } "); } [WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestAbstractMethod() { await VerifyCS.VerifyCodeFixAsync(@" public abstract class TestClass { abstract string {|CS0621:[|Test|]|} { get; } } ", @" public abstract class TestClass { protected abstract string Test { get; } } "); } [WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestOverriddenMethod() { await VerifyCS.VerifyCodeFixAsync(@" public abstract class TestClass { public abstract string Test { get; } } public class Derived : TestClass { override string {|CS0507:{|CS0621:[|Test|]|}|} { get; } } ", @" public abstract class TestClass { public abstract string Test { get; } } public class Derived : TestClass { public override string Test { get; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] public async Task TestFileScopedNamespaces() { await new VerifyCS.Test { TestCode = @" namespace Test; struct [|S1|] { } ", FixedCode = @" namespace Test; internal struct S1 { } ", LanguageVersion = LanguageVersion.CSharp10, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)] [WorkItem(55703, "https://github.com/dotnet/roslyn/issues/55703")] public async Task TestPartial_WithExistingModifier() { var source = @" partial class [|C|] { } public partial class C { } "; var fixedSource = @" public partial class C { } public partial class C { } "; var test = new VerifyCS.Test { TestCode = source, FixedCode = fixedSource, LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.Preview, }; await test.RunAsync(); } } }
1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/EditorFeatures/CSharpTest/Formatting/CSharpNewDocumentFormattingServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Test.Utilities.Formatting; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests { protected override string Language => LanguageNames.CSharp; protected override TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions) => TestWorkspace.CreateCSharp(testCode, parseOptions); [Fact] public async Task TestFileScopedNamespaces() { await TestAsync(testCode: @" namespace Goo { internal class C { } }", expected: @" namespace Goo; internal class C { } ", options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); } [Fact] public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces() { var testCode = @" namespace Goo { } namespace Bar { }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); } [Fact] public async Task TestFileScopedNamespaces_Invalid_WrongLanguageVersion() { var testCode = @" namespace Goo { internal class C { } }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9)); } [Fact] public async Task TestBlockScopedNamespaces() { await TestAsync(testCode: @" namespace Goo; internal class C { } ", expected: @" namespace Goo { internal class C { } }", options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error)) }); } [Fact] public async Task TestOrganizeUsingsWithNoUsings() { var testCode = @"namespace Goo { }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error)) }); } [Fact] public async Task TestFileBanners() { await TestAsync(testCode: @"using System; namespace Goo { }", expected: @"// This is a banner. using System; namespace Goo { }", options: new[] { (CodeStyleOptions2.FileHeaderTemplate, "This is a banner.") }); } [Fact] public async Task TestAccessibilityModifiers() { await TestAsync(testCode: @"using System; namespace Goo { class C { } }", expected: @"using System; namespace Goo { internal class C { } }", options: new[] { (CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error)) }); } [Fact] public async Task TestUsingDirectivePlacement() { await TestAsync(testCode: @"using System; namespace Goo { }", expected: @"namespace Goo { using System; }", options: new[] { (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error)) }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities.Formatting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting { public class CSharpNewDocumentFormattingServiceTests : AbstractNewDocumentFormattingServiceTests { protected override string Language => LanguageNames.CSharp; protected override TestWorkspace CreateTestWorkspace(string testCode, ParseOptions? parseOptions) => TestWorkspace.CreateCSharp(testCode, parseOptions); [Fact] public async Task TestFileScopedNamespaces() { await TestAsync(testCode: @" namespace Goo { internal class C { } }", expected: @" namespace Goo; internal class C { } ", options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); } [Fact] public async Task TestFileScopedNamespaces_Invalid_MultipleNamespaces() { var testCode = @" namespace Goo { } namespace Bar { }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp10)); } [Fact] public async Task TestFileScopedNamespaces_Invalid_WrongLanguageVersion() { var testCode = @" namespace Goo { internal class C { } }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.FileScoped, NotificationOption2.Error)) }, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9)); } [Fact] public async Task TestBlockScopedNamespaces() { await TestAsync(testCode: @" namespace Goo; internal class C { } ", expected: @" namespace Goo { internal class C { } }", options: new[] { (CSharpCodeStyleOptions.NamespaceDeclarations, new CodeStyleOption2<NamespaceDeclarationPreference>(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Error)) }); } [Fact] public async Task TestOrganizeUsingsWithNoUsings() { var testCode = @"namespace Goo { }"; await TestAsync( testCode: testCode, expected: testCode, options: new[] { (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, NotificationOption2.Error)) }); } [Fact] public async Task TestFileBanners() { await TestAsync(testCode: @"using System; namespace Goo { }", expected: @"// This is a banner. using System; namespace Goo { }", options: new[] { (CodeStyleOptions2.FileHeaderTemplate, "This is a banner.") }); } [Fact] public async Task TestAccessibilityModifiers() { await TestAsync(testCode: @"using System; namespace Goo { class C { } }", expected: @"using System; namespace Goo { internal class C { } }", options: new[] { (CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error)) }); } [Fact] [WorkItem(55703, "https://github.com/dotnet/roslyn/issues/55703")] public async Task TestAccessibilityModifiers_IgnoresPartial() { await TestAsync( testCode: @"using System; namespace Goo { class E { } partial class C { } class D { } }", expected: @"using System; namespace Goo { internal class E { } partial class C { } internal class D { } }", options: new[] { (CodeStyleOptions2.RequireAccessibilityModifiers, new CodeStyleOption2<AccessibilityModifiersRequired>(AccessibilityModifiersRequired.Always, NotificationOption2.Error)) }); } [Fact] public async Task TestUsingDirectivePlacement() { await TestAsync(testCode: @"using System; namespace Goo { }", expected: @"namespace Goo { using System; }", options: new[] { (CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, NotificationOption2.Error)) }); } } }
1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Formatting { [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared] internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAccessibilityModifiersNewDocumentFormattingProvider() { } public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language); if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never) { return document; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node)); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var service = document.GetRequiredLanguageService<IAddAccessibilityModifiersService>(); foreach (var declaration in typeDeclarations) { if (!service.ShouldUpdateAccessibilityModifier(syntaxFacts, declaration, accessibilityPreferences.Value, out _)) continue; var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken); if (type == null) continue; AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Formatting { [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared] internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAccessibilityModifiersNewDocumentFormattingProvider() { } public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language); if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never) { return document; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node)); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var service = document.GetRequiredLanguageService<IAddAccessibilityModifiersService>(); foreach (var declaration in typeDeclarations) { if (!service.ShouldUpdateAccessibilityModifier(syntaxFacts, declaration, accessibilityPreferences.Value, out _)) continue; // Since we format each document as they are added to a project we can't assume we know about all // of the files that are coming, so we have to opt out of changing partial classes. This especially // manifests when creating new projects as we format before we have a project at all, so we could get a // situation like this: // // File1.cs: // partial class C { } // File2.cs: // public partial class C { } // // When we see File1, we don't know about File2, so would add an internal modifier, which would result in a compile // error. var modifiers = syntaxFacts.GetModifiers(declaration); syntaxFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _); if (declarationModifiers.IsPartial) continue; var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken); if (type == null) continue; AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } } }
1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpWinForms.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpWinForms : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpWinForms(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpWinForms), WellKnownProjectTemplates.WinFormsApplication) { } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void AddControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.SolutionExplorer.SaveFile(project, "Form1.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Name = ""SomeButton""", actualText); Assert.Contains(@"private System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeControlProperty() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "NewButtonText"); VisualStudio.SolutionExplorer.CloseDesignerFile(project, "Form1.cs", saveFile: true); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Text = ""NewButtonText""", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeControlPropertyInCode() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "ButtonTextGoesHere"); var expectedPropertyValue = "ButtonTextGoesHere"; var actualPropertyValue = VisualStudio.Editor.GetWinFormButtonPropertyValue(buttonName: "SomeButton", propertyName: "Text"); Assert.Equal(expectedPropertyValue, actualPropertyValue); VisualStudio.SolutionExplorer.CloseDesignerFile(project, "Form1.cs", saveFile: true); // Change the control's text in designer.cs code VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); // Verify that the control's property was set correctly. The following text should appear in InitializeComponent(). var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Text = ""ButtonTextGoesHere"";", actualText); // Replace text property with something else VisualStudio.Editor.SelectTextInCurrentDocument(@"this.SomeButton.Text = ""ButtonTextGoesHere"";"); VisualStudio.Editor.SendKeys(@"this.SomeButton.Text = ""GibberishText"";"); VisualStudio.SolutionExplorer.CloseCodeFile(project, "Form1.Designer.cs", saveFile: true); // Verify that the control text has changed in the designer VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); expectedPropertyValue = "GibberishText"; actualPropertyValue = VisualStudio.Editor.GetWinFormButtonPropertyValue(buttonName: "SomeButton", propertyName: "Text"); Assert.Equal(expectedPropertyValue, actualPropertyValue); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void AddClickHandler() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "ExecuteWhenButtonClicked"); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var designerActualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Click += new System.EventHandler(this.ExecuteWhenButtonClicked);", designerActualText); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.cs"); var codeFileActualText = VisualStudio.Editor.GetText(); Assert.Contains(@" public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void ExecuteWhenButtonClicked(object sender, EventArgs e) { } }", codeFileActualText); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/55703"), Trait(Traits.Feature, Traits.Features.WinForms)] public void RenameControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); // Add some control properties and events VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "ButtonTextValue"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "SomeButtonHandler"); // Rename the control VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Name", propertyValue: "SomeNewButton"); VisualStudio.ErrorList.Verify.NoBuildErrors(); // Verify that the rename propagated in designer code VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeNewButton.Name = ""SomeNewButton"";", actualText); Assert.Contains(@"this.SomeNewButton.Text = ""ButtonTextValue"";", actualText); Assert.Contains(@"this.SomeNewButton.Click += new System.EventHandler(this.SomeButtonHandler);", actualText); Assert.Contains(@"private System.Windows.Forms.Button SomeNewButton;", actualText); // Verify that the old button name goes away Assert.DoesNotContain(@"private System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void RemoveEventHandler() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "GooHandler"); // Remove the event handler VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: ""); VisualStudio.ErrorList.Verify.NoBuildErrors(); // Verify that the handler is removed VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.DoesNotContain(@"VisualStudio.Editor.SomeButton.Click += new System.EventHandler(VisualStudio.Editor.GooHandler);", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeAccessibility() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Modifiers", propertyTypeName: "System.CodeDom.MemberAttributes", propertyValue: "Public"); VisualStudio.ErrorList.Verify.NoBuildErrors(); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"public System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void DeleteControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.DeleteWinFormButton("SomeButton"); VisualStudio.ErrorList.Verify.NoBuildErrors(); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.DoesNotContain(@"VisualStudio.Editor.SomeButton.Name = ""SomeButton"";", actualText); Assert.DoesNotContain(@"private System.Windows.Forms.Button SomeButton;", actualText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpWinForms : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpWinForms(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpWinForms), WellKnownProjectTemplates.WinFormsApplication) { } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void AddControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.SolutionExplorer.SaveFile(project, "Form1.cs"); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Name = ""SomeButton""", actualText); Assert.Contains(@"private System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeControlProperty() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "NewButtonText"); VisualStudio.SolutionExplorer.CloseDesignerFile(project, "Form1.cs", saveFile: true); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Text = ""NewButtonText""", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeControlPropertyInCode() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "ButtonTextGoesHere"); var expectedPropertyValue = "ButtonTextGoesHere"; var actualPropertyValue = VisualStudio.Editor.GetWinFormButtonPropertyValue(buttonName: "SomeButton", propertyName: "Text"); Assert.Equal(expectedPropertyValue, actualPropertyValue); VisualStudio.SolutionExplorer.CloseDesignerFile(project, "Form1.cs", saveFile: true); // Change the control's text in designer.cs code VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); // Verify that the control's property was set correctly. The following text should appear in InitializeComponent(). var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Text = ""ButtonTextGoesHere"";", actualText); // Replace text property with something else VisualStudio.Editor.SelectTextInCurrentDocument(@"this.SomeButton.Text = ""ButtonTextGoesHere"";"); VisualStudio.Editor.SendKeys(@"this.SomeButton.Text = ""GibberishText"";"); VisualStudio.SolutionExplorer.CloseCodeFile(project, "Form1.Designer.cs", saveFile: true); // Verify that the control text has changed in the designer VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); expectedPropertyValue = "GibberishText"; actualPropertyValue = VisualStudio.Editor.GetWinFormButtonPropertyValue(buttonName: "SomeButton", propertyName: "Text"); Assert.Equal(expectedPropertyValue, actualPropertyValue); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void AddClickHandler() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "ExecuteWhenButtonClicked"); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var designerActualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeButton.Click += new System.EventHandler(this.ExecuteWhenButtonClicked);", designerActualText); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.cs"); var codeFileActualText = VisualStudio.Editor.GetText(); Assert.Contains(@" public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void ExecuteWhenButtonClicked(object sender, EventArgs e) { } }", codeFileActualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void RenameControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); // Add some control properties and events VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Text", propertyValue: "ButtonTextValue"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "SomeButtonHandler"); // Rename the control VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Name", propertyValue: "SomeNewButton"); VisualStudio.ErrorList.Verify.NoBuildErrors(); // Verify that the rename propagated in designer code VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"this.SomeNewButton.Name = ""SomeNewButton"";", actualText); Assert.Contains(@"this.SomeNewButton.Text = ""ButtonTextValue"";", actualText); Assert.Contains(@"this.SomeNewButton.Click += new System.EventHandler(this.SomeButtonHandler);", actualText); Assert.Contains(@"private System.Windows.Forms.Button SomeNewButton;", actualText); // Verify that the old button name goes away Assert.DoesNotContain(@"private System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void RemoveEventHandler() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: "GooHandler"); // Remove the event handler VisualStudio.Editor.EditWinFormButtonEvent(buttonName: "SomeButton", eventName: "Click", eventHandlerName: ""); VisualStudio.ErrorList.Verify.NoBuildErrors(); // Verify that the handler is removed VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.DoesNotContain(@"VisualStudio.Editor.SomeButton.Click += new System.EventHandler(VisualStudio.Editor.GooHandler);", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void ChangeAccessibility() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.EditWinFormButtonProperty(buttonName: "SomeButton", propertyName: "Modifiers", propertyTypeName: "System.CodeDom.MemberAttributes", propertyValue: "Public"); VisualStudio.ErrorList.Verify.NoBuildErrors(); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"public System.Windows.Forms.Button SomeButton;", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.WinForms)] public void DeleteControl() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFileWithDesigner(project, "Form1.cs"); VisualStudio.Editor.AddWinFormButton("SomeButton"); VisualStudio.Editor.DeleteWinFormButton("SomeButton"); VisualStudio.ErrorList.Verify.NoBuildErrors(); VisualStudio.SolutionExplorer.OpenFile(project, "Form1.Designer.cs"); var actualText = VisualStudio.Editor.GetText(); Assert.DoesNotContain(@"VisualStudio.Editor.SomeButton.Name = ""SomeButton"";", actualText); Assert.DoesNotContain(@"private System.Windows.Forms.Button SomeButton;", actualText); } } }
1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/GenerateMember/GenerateEnumMember/CSharpGenerateEnumMemberService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateEnumMember { [ExportLanguageService(typeof(IGenerateEnumMemberService), LanguageNames.CSharp), Shared] internal partial class CSharpGenerateEnumMemberService : AbstractGenerateEnumMemberService<CSharpGenerateEnumMemberService, SimpleNameSyntax, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateEnumMemberService() { } protected override bool IsIdentifierNameGeneration(SyntaxNode node) => node is IdentifierNameSyntax; protected override bool TryInitializeIdentifierNameState( SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression) { identifierToken = identifierName.Identifier; if (identifierToken.ValueText != string.Empty && !identifierName.IsVar) { simpleNameOrMemberAccessExpression = identifierName.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == identifierName ? (ExpressionSyntax)memberAccess : identifierName; // If we're being invoked, then don't offer this, offer generate method instead. // Note: we could offer to generate a field with a delegate type. However, that's // very esoteric and probably not what most users want. if (simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.ObjectCreationExpression) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.GotoStatement) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.AliasQualifiedName)) { return false; } return true; } identifierToken = default; simpleNameOrMemberAccessExpression = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateEnumMember { [ExportLanguageService(typeof(IGenerateEnumMemberService), LanguageNames.CSharp), Shared] internal partial class CSharpGenerateEnumMemberService : AbstractGenerateEnumMemberService<CSharpGenerateEnumMemberService, SimpleNameSyntax, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateEnumMemberService() { } protected override bool IsIdentifierNameGeneration(SyntaxNode node) => node is IdentifierNameSyntax; protected override bool TryInitializeIdentifierNameState( SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken, out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression) { identifierToken = identifierName.Identifier; if (identifierToken.ValueText != string.Empty && !identifierName.IsVar) { simpleNameOrMemberAccessExpression = identifierName.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == identifierName ? (ExpressionSyntax)memberAccess : identifierName; // If we're being invoked, then don't offer this, offer generate method instead. // Note: we could offer to generate a field with a delegate type. However, that's // very esoteric and probably not what most users want. if (simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.ObjectCreationExpression) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.GotoStatement) || simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.AliasQualifiedName)) { return false; } return true; } identifierToken = default; simpleNameOrMemberAccessExpression = null; return false; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Workspaces/Core/Portable/Classification/SyntaxClassification/AbstractNameSyntaxClassifier.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractNameSyntaxClassifier : AbstractSyntaxClassifier { protected abstract int? GetRightmostNameArity(SyntaxNode node); protected abstract bool IsParentAnAttribute(SyntaxNode node); protected ISymbol? TryGetSymbol(SyntaxNode node, SymbolInfo symbolInfo, SemanticModel semanticModel) { var symbol = symbolInfo.Symbol; if (symbol is null && symbolInfo.CandidateSymbols.Length > 0) { var firstSymbol = symbolInfo.CandidateSymbols[0]; switch (symbolInfo.CandidateReason) { case CandidateReason.NotAValue: return firstSymbol; case CandidateReason.NotCreatable: // We want to color types even if they can't be constructed. if (firstSymbol.IsConstructor() || firstSymbol is ITypeSymbol) { symbol = firstSymbol; } break; case CandidateReason.OverloadResolutionFailure: // If we couldn't bind to a constructor, still classify the type. if (firstSymbol.IsConstructor()) { symbol = firstSymbol; } break; case CandidateReason.Inaccessible: // If a constructor wasn't accessible, still classify the type if it's accessible. if (firstSymbol.IsConstructor() && semanticModel.IsAccessible(node.SpanStart, firstSymbol.ContainingType)) { symbol = firstSymbol; } break; case CandidateReason.WrongArity: var arity = GetRightmostNameArity(node); if (arity.HasValue && arity.Value == 0) { // When the user writes something like "IList" we don't want to *not* classify // just because the type bound to "IList<T>". This is also important for use // cases like "Add-using" where it can be confusing when the using is added for // "using System.Collection.Generic" but then the type name still does not classify. symbol = firstSymbol; } break; } } // Classify a reference to an attribute constructor in an attribute location // as if we were classifying the attribute type itself. if (symbol.IsConstructor() && IsParentAnAttribute(node)) { symbol = symbol.ContainingType; } return symbol; } protected static void TryClassifyStaticSymbol( ISymbol? symbol, TextSpan span, ArrayBuilder<ClassifiedSpan> result) { if (!IsStaticSymbol(symbol)) { return; } result.Add(new ClassifiedSpan(span, ClassificationTypeNames.StaticSymbol)); } protected static bool IsStaticSymbol(ISymbol? symbol) { if (symbol is null || !symbol.IsStatic) { return false; } if (symbol.IsEnumMember()) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsNamespace()) { // Namespace names are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsLocalFunction()) { // Local function names are not classified as static since the // the symbol returning true for IsStatic is an implementation detail. return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractNameSyntaxClassifier : AbstractSyntaxClassifier { protected abstract int? GetRightmostNameArity(SyntaxNode node); protected abstract bool IsParentAnAttribute(SyntaxNode node); protected ISymbol? TryGetSymbol(SyntaxNode node, SymbolInfo symbolInfo, SemanticModel semanticModel) { var symbol = symbolInfo.Symbol; if (symbol is null && symbolInfo.CandidateSymbols.Length > 0) { var firstSymbol = symbolInfo.CandidateSymbols[0]; switch (symbolInfo.CandidateReason) { case CandidateReason.NotAValue: return firstSymbol; case CandidateReason.NotCreatable: // We want to color types even if they can't be constructed. if (firstSymbol.IsConstructor() || firstSymbol is ITypeSymbol) { symbol = firstSymbol; } break; case CandidateReason.OverloadResolutionFailure: // If we couldn't bind to a constructor, still classify the type. if (firstSymbol.IsConstructor()) { symbol = firstSymbol; } break; case CandidateReason.Inaccessible: // If a constructor wasn't accessible, still classify the type if it's accessible. if (firstSymbol.IsConstructor() && semanticModel.IsAccessible(node.SpanStart, firstSymbol.ContainingType)) { symbol = firstSymbol; } break; case CandidateReason.WrongArity: var arity = GetRightmostNameArity(node); if (arity.HasValue && arity.Value == 0) { // When the user writes something like "IList" we don't want to *not* classify // just because the type bound to "IList<T>". This is also important for use // cases like "Add-using" where it can be confusing when the using is added for // "using System.Collection.Generic" but then the type name still does not classify. symbol = firstSymbol; } break; } } // Classify a reference to an attribute constructor in an attribute location // as if we were classifying the attribute type itself. if (symbol.IsConstructor() && IsParentAnAttribute(node)) { symbol = symbol.ContainingType; } return symbol; } protected static void TryClassifyStaticSymbol( ISymbol? symbol, TextSpan span, ArrayBuilder<ClassifiedSpan> result) { if (!IsStaticSymbol(symbol)) { return; } result.Add(new ClassifiedSpan(span, ClassificationTypeNames.StaticSymbol)); } protected static bool IsStaticSymbol(ISymbol? symbol) { if (symbol is null || !symbol.IsStatic) { return false; } if (symbol.IsEnumMember()) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsNamespace()) { // Namespace names are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsLocalFunction()) { // Local function names are not classified as static since the // the symbol returning true for IsStatic is an implementation detail. return false; } return true; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/Core/Portable/Completion/Providers/MemberInsertingCompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; namespace Microsoft.CodeAnalysis.Completion.Providers { internal class MemberInsertionCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, DeclarationModifiers modifiers, int line, ISymbol symbol, SyntaxToken token, int descriptionPosition, CompletionItemRules rules) { var props = ImmutableDictionary<string, string>.Empty .Add("Line", line.ToString()) .Add("Modifiers", modifiers.ToString()) .Add("TokenSpanEnd", token.Span.End.ToString()); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, symbols: ImmutableArray.Create(symbol), contextPosition: descriptionPosition, properties: props, rules: rules, isComplexTextEdit: true); } public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public static DeclarationModifiers GetModifiers(CompletionItem item) { if (item.Properties.TryGetValue("Modifiers", out var text) && DeclarationModifiers.TryParse(text, out var modifiers)) { return modifiers; } return default; } public static int GetLine(CompletionItem item) { if (item.Properties.TryGetValue("Line", out var text) && int.TryParse(text, out var number)) { return number; } return 0; } public static int GetTokenSpanEnd(CompletionItem item) { if (item.Properties.TryGetValue("TokenSpanEnd", out var text) && int.TryParse(text, out var number)) { return number; } return 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Completion.Providers { internal class MemberInsertionCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, DeclarationModifiers modifiers, int line, ISymbol symbol, SyntaxToken token, int descriptionPosition, CompletionItemRules rules) { var props = ImmutableDictionary<string, string>.Empty .Add("Line", line.ToString()) .Add("Modifiers", modifiers.ToString()) .Add("TokenSpanEnd", token.Span.End.ToString()); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, symbols: ImmutableArray.Create(symbol), contextPosition: descriptionPosition, properties: props, rules: rules, isComplexTextEdit: true); } public static Task<CompletionDescription> GetDescriptionAsync(CompletionItem item, Document document, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public static DeclarationModifiers GetModifiers(CompletionItem item) { if (item.Properties.TryGetValue("Modifiers", out var text) && DeclarationModifiers.TryParse(text, out var modifiers)) { return modifiers; } return default; } public static int GetLine(CompletionItem item) { if (item.Properties.TryGetValue("Line", out var text) && int.TryParse(text, out var number)) { return number; } return 0; } public static int GetTokenSpanEnd(CompletionItem item) { if (item.Properties.TryGetValue("TokenSpanEnd", out var text) && int.TryParse(text, out var number)) { return number; } return 0; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/CSharp/Portable/Binder/InMethodBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder for a method body, which places the method's parameters in scope /// and notes if the method is an iterator method. /// Note: instances of this type can be re-used across different attempts at compiling the same method (caching by binder factory). /// </summary> internal sealed class InMethodBinder : LocalScopeBinder { private MultiDictionary<string, ParameterSymbol> _lazyParameterMap; private readonly MethodSymbol _methodSymbol; private SmallDictionary<string, Symbol> _lazyDefinitionMap; private TypeWithAnnotations.Boxed _iteratorElementType; public InMethodBinder(MethodSymbol owner, Binder enclosing) : base(enclosing, enclosing.Flags & ~BinderFlags.AllClearedAtExecutableCodeBoundary) { Debug.Assert(!enclosing.Flags.Includes(BinderFlags.InCatchFilter)); Debug.Assert((object)owner != null); _methodSymbol = owner; } private static void RecordDefinition<T>(SmallDictionary<string, Symbol> declarationMap, ImmutableArray<T> definitions) where T : Symbol { foreach (Symbol s in definitions) { if (!declarationMap.ContainsKey(s.Name)) { declarationMap.Add(s.Name, s); } } } protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return null; } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return null; } internal override uint LocalScopeDepth => Binder.TopLevelScope; protected override bool InExecutableBinder => true; internal override Symbol ContainingMemberOrLambda { get { return _methodSymbol; } } internal override bool IsInMethodBody { get { return true; } } internal override bool IsNestedFunctionBinder => _methodSymbol.MethodKind == MethodKind.LocalFunction; internal override bool IsDirectlyInIterator { get { return _methodSymbol.IsIterator; } } internal override bool IsIndirectlyInIterator { get { return IsDirectlyInIterator; // Sic: indirectly iff directly } } internal override GeneratedLabelSymbol BreakLabel { get { return null; } } internal override GeneratedLabelSymbol ContinueLabel { get { return null; } } protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { } internal override TypeWithAnnotations GetIteratorElementType() { RefKind refKind = _methodSymbol.RefKind; TypeSymbol returnType = _methodSymbol.ReturnType; if (!this.IsDirectlyInIterator) { // This should only happen when speculating, but we don't have a good way to assert that since the // original binder isn't available here. // If we're speculating about a yield statement inside a non-iterator method, we'll try to be nice // and deduce an iterator element type from the return type. If we didn't do this, the // TypeInfo.ConvertedType of the yield statement would always be an error type. However, we will // not mutate any state (i.e. we won't store the result). var elementType = GetIteratorElementTypeFromReturnType(Compilation, refKind, returnType, errorLocation: null, diagnostics: null); return !elementType.IsDefault ? elementType : TypeWithAnnotations.Create(CreateErrorType()); } if (_iteratorElementType is null) { TypeWithAnnotations elementType = GetIteratorElementTypeFromReturnType(Compilation, refKind, returnType, errorLocation: null, diagnostics: null); if (elementType.IsDefault) { elementType = TypeWithAnnotations.Create(CreateErrorType()); } Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(elementType), null); } return _iteratorElementType.Value; } internal static TypeWithAnnotations GetIteratorElementTypeFromReturnType(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType, Location errorLocation, BindingDiagnosticBag diagnostics) { if (refKind == RefKind.None && returnType.Kind == SymbolKind.NamedType) { TypeSymbol originalDefinition = returnType.OriginalDefinition; switch (originalDefinition.SpecialType) { case SpecialType.System_Collections_IEnumerable: case SpecialType.System_Collections_IEnumerator: var objectType = compilation.GetSpecialType(SpecialType.System_Object); if (diagnostics != null) { ReportUseSite(objectType, diagnostics, errorLocation); } return TypeWithAnnotations.Create(objectType); case SpecialType.System_Collections_Generic_IEnumerable_T: case SpecialType.System_Collections_Generic_IEnumerator_T: return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T), TypeCompareKind.ConsiderEverything)) { return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } } return default; } internal static bool IsAsyncStreamInterface(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType) { if (refKind == RefKind.None && returnType.Kind == SymbolKind.NamedType) { TypeSymbol originalDefinition = returnType.OriginalDefinition; if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T), TypeCompareKind.ConsiderEverything)) { return true; } } return false; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if (_methodSymbol.ParameterCount == 0 || (options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } var parameterMap = _lazyParameterMap; if (parameterMap == null) { var parameters = _methodSymbol.Parameters; parameterMap = new MultiDictionary<string, ParameterSymbol>(parameters.Length, EqualityComparer<string>.Default); foreach (var parameter in parameters) { parameterMap.Add(parameter.Name, parameter); } _lazyParameterMap = parameterMap; } foreach (var parameterSymbol in parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(parameterSymbol, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var parameter in _methodSymbol.Parameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } private static bool ReportConflictWithParameter(Symbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { #if DEBUG var locations = parameter.Locations; Debug.Assert(!locations.IsEmpty || parameter.IsImplicitlyDeclared); var oldLocation = locations.FirstOrNone(); Debug.Assert(oldLocation != newLocation || oldLocation == Location.None || newLocation.SourceTree?.GetRoot().ContainsDiagnostics == true, "same nonempty location refers to different symbols?"); #endif SymbolKind parameterKind = parameter.Kind; // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) { return true; } if (parameterKind == SymbolKind.Parameter) { switch (newSymbolKind) { case SymbolKind.Parameter: case SymbolKind.Local: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.Method: if (((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction) { goto case SymbolKind.Parameter; } break; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } } if (parameterKind == SymbolKind.TypeParameter) { switch (newSymbolKind) { case SymbolKind.Parameter: case SymbolKind.Local: // CS0412: '{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name); return true; case SymbolKind.Method: if (((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction) { goto case SymbolKind.Parameter; } break; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are detected elsewhere return false; case SymbolKind.RangeVariable: // The range variable '{0}' cannot have the same name as a method type parameter diagnostics.Add(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, newLocation, name); return true; } } Debug.Assert(false, "what else could be defined in a method?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return true; } internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { var parameters = _methodSymbol.Parameters; var typeParameters = _methodSymbol.TypeParameters; if (parameters.IsEmpty && typeParameters.IsEmpty) { return false; } var map = _lazyDefinitionMap; if (map == null) { map = new SmallDictionary<string, Symbol>(); RecordDefinition(map, parameters); RecordDefinition(map, typeParameters); _lazyDefinitionMap = map; } Symbol existingDeclaration; if (map.TryGetValue(name, out existingDeclaration)) { return ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder for a method body, which places the method's parameters in scope /// and notes if the method is an iterator method. /// Note: instances of this type can be re-used across different attempts at compiling the same method (caching by binder factory). /// </summary> internal sealed class InMethodBinder : LocalScopeBinder { private MultiDictionary<string, ParameterSymbol> _lazyParameterMap; private readonly MethodSymbol _methodSymbol; private SmallDictionary<string, Symbol> _lazyDefinitionMap; private TypeWithAnnotations.Boxed _iteratorElementType; public InMethodBinder(MethodSymbol owner, Binder enclosing) : base(enclosing, enclosing.Flags & ~BinderFlags.AllClearedAtExecutableCodeBoundary) { Debug.Assert(!enclosing.Flags.Includes(BinderFlags.InCatchFilter)); Debug.Assert((object)owner != null); _methodSymbol = owner; } private static void RecordDefinition<T>(SmallDictionary<string, Symbol> declarationMap, ImmutableArray<T> definitions) where T : Symbol { foreach (Symbol s in definitions) { if (!declarationMap.ContainsKey(s.Name)) { declarationMap.Add(s.Name, s); } } } protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return null; } protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return null; } internal override uint LocalScopeDepth => Binder.TopLevelScope; protected override bool InExecutableBinder => true; internal override Symbol ContainingMemberOrLambda { get { return _methodSymbol; } } internal override bool IsInMethodBody { get { return true; } } internal override bool IsNestedFunctionBinder => _methodSymbol.MethodKind == MethodKind.LocalFunction; internal override bool IsDirectlyInIterator { get { return _methodSymbol.IsIterator; } } internal override bool IsIndirectlyInIterator { get { return IsDirectlyInIterator; // Sic: indirectly iff directly } } internal override GeneratedLabelSymbol BreakLabel { get { return null; } } internal override GeneratedLabelSymbol ContinueLabel { get { return null; } } protected override void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { } internal override TypeWithAnnotations GetIteratorElementType() { RefKind refKind = _methodSymbol.RefKind; TypeSymbol returnType = _methodSymbol.ReturnType; if (!this.IsDirectlyInIterator) { // This should only happen when speculating, but we don't have a good way to assert that since the // original binder isn't available here. // If we're speculating about a yield statement inside a non-iterator method, we'll try to be nice // and deduce an iterator element type from the return type. If we didn't do this, the // TypeInfo.ConvertedType of the yield statement would always be an error type. However, we will // not mutate any state (i.e. we won't store the result). var elementType = GetIteratorElementTypeFromReturnType(Compilation, refKind, returnType, errorLocation: null, diagnostics: null); return !elementType.IsDefault ? elementType : TypeWithAnnotations.Create(CreateErrorType()); } if (_iteratorElementType is null) { TypeWithAnnotations elementType = GetIteratorElementTypeFromReturnType(Compilation, refKind, returnType, errorLocation: null, diagnostics: null); if (elementType.IsDefault) { elementType = TypeWithAnnotations.Create(CreateErrorType()); } Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(elementType), null); } return _iteratorElementType.Value; } internal static TypeWithAnnotations GetIteratorElementTypeFromReturnType(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType, Location errorLocation, BindingDiagnosticBag diagnostics) { if (refKind == RefKind.None && returnType.Kind == SymbolKind.NamedType) { TypeSymbol originalDefinition = returnType.OriginalDefinition; switch (originalDefinition.SpecialType) { case SpecialType.System_Collections_IEnumerable: case SpecialType.System_Collections_IEnumerator: var objectType = compilation.GetSpecialType(SpecialType.System_Object); if (diagnostics != null) { ReportUseSite(objectType, diagnostics, errorLocation); } return TypeWithAnnotations.Create(objectType); case SpecialType.System_Collections_Generic_IEnumerable_T: case SpecialType.System_Collections_Generic_IEnumerator_T: return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T), TypeCompareKind.ConsiderEverything)) { return ((NamedTypeSymbol)returnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; } } return default; } internal static bool IsAsyncStreamInterface(CSharpCompilation compilation, RefKind refKind, TypeSymbol returnType) { if (refKind == RefKind.None && returnType.Kind == SymbolKind.NamedType) { TypeSymbol originalDefinition = returnType.OriginalDefinition; if (TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T), TypeCompareKind.ConsiderEverything) || TypeSymbol.Equals(originalDefinition, compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T), TypeCompareKind.ConsiderEverything)) { return true; } } return false; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if (_methodSymbol.ParameterCount == 0 || (options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } var parameterMap = _lazyParameterMap; if (parameterMap == null) { var parameters = _methodSymbol.Parameters; parameterMap = new MultiDictionary<string, ParameterSymbol>(parameters.Length, EqualityComparer<string>.Default); foreach (var parameter in parameters) { parameterMap.Add(parameter.Name, parameter); } _lazyParameterMap = parameterMap; } foreach (var parameterSymbol in parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(parameterSymbol, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var parameter in _methodSymbol.Parameters) { if (originalBinder.CanAddLookupSymbolInfo(parameter, options, result, null)) { result.AddSymbol(parameter, parameter.Name, 0); } } } } private static bool ReportConflictWithParameter(Symbol parameter, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics) { #if DEBUG var locations = parameter.Locations; Debug.Assert(!locations.IsEmpty || parameter.IsImplicitlyDeclared); var oldLocation = locations.FirstOrNone(); Debug.Assert(oldLocation != newLocation || oldLocation == Location.None || newLocation.SourceTree?.GetRoot().ContainsDiagnostics == true, "same nonempty location refers to different symbols?"); #endif SymbolKind parameterKind = parameter.Kind; // Quirk of the way we represent lambda parameters. SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind; if (newSymbolKind == SymbolKind.ErrorType) { return true; } if (parameterKind == SymbolKind.Parameter) { switch (newSymbolKind) { case SymbolKind.Parameter: case SymbolKind.Local: // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name); return true; case SymbolKind.Method: if (((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction) { goto case SymbolKind.Parameter; } break; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are not reported, for backwards compatibility. return false; case SymbolKind.RangeVariable: // The range variable '{0}' conflicts with a previous declaration of '{0}' diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name); return true; } } if (parameterKind == SymbolKind.TypeParameter) { switch (newSymbolKind) { case SymbolKind.Parameter: case SymbolKind.Local: // CS0412: '{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name); return true; case SymbolKind.Method: if (((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction) { goto case SymbolKind.Parameter; } break; case SymbolKind.TypeParameter: // Type parameter declaration name conflicts are detected elsewhere return false; case SymbolKind.RangeVariable: // The range variable '{0}' cannot have the same name as a method type parameter diagnostics.Add(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, newLocation, name); return true; } } Debug.Assert(false, "what else could be defined in a method?"); diagnostics.Add(ErrorCode.ERR_InternalError, newLocation); return true; } internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics) { var parameters = _methodSymbol.Parameters; var typeParameters = _methodSymbol.TypeParameters; if (parameters.IsEmpty && typeParameters.IsEmpty) { return false; } var map = _lazyDefinitionMap; if (map == null) { map = new SmallDictionary<string, Symbol>(); RecordDefinition(map, parameters); RecordDefinition(map, typeParameters); _lazyDefinitionMap = map; } Symbol existingDeclaration; if (map.TryGetValue(name, out existingDeclaration)) { return ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics); } return false; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/NotnullKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotNullKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext> { public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsTypeParameterConstraintContext(position, context.LeftToken) ? ImmutableArray.Create(new RecommendedKeyword("notnull")) : ImmutableArray<RecommendedKeyword>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotNullKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext> { public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsTypeParameterConstraintContext(position, context.LeftToken) ? ImmutableArray.Create(new RecommendedKeyword("notnull")) : ImmutableArray<RecommendedKeyword>.Empty; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Scripting/Core/Hosting/CommandLine/NotImplementedAnalyzerLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class NotImplementedAnalyzerLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { throw new NotImplementedException(); } public Assembly LoadFromPath(string fullPath) { 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.Reflection; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal sealed class NotImplementedAnalyzerLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { throw new NotImplementedException(); } public Assembly LoadFromPath(string fullPath) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { [UseExportProvider] public class SplitStringLiteralCommandHandlerTests { /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestWorker( string inputMarkup, string expectedOutputMarkup, Action callback, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { using var workspace = TestWorkspace.CreateCSharp(inputMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); if (useTabs && expectedOutputMarkup != null) { Assert.Contains("\t", expectedOutputMarkup); } var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) { snapshotSpans.Add(selection.ToSnapshotSpan(originalSnapshot)); } view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitStringLiteralCommandHandler>(nameof(SplitStringLiteralCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.First().Start, view.Caret.Position.BufferPosition.Position); if (verifyUndo) { // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); Assert.Equal(originalSelections.First().Start, view.Caret.Position.BufferPosition.Position); } } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestHandled( string inputMarkup, string expectedOutputMarkup, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, verifyUndo, indentStyle, useTabs); } private static void TestNotHandled(string inputMarkup) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }); Assert.True(notHandled); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeString() { TestNotHandled( @"class C { void M() { var v = [||]""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeInterpolatedString() { TestNotHandled( @"class C { void M() { var v = [||]$""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_1() { TestNotHandled( @"class C { void M() { var v = """"[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_2() { TestNotHandled( @"class C { void M() { var v = """" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_3() { TestNotHandled( @"class C { void M() { var v = """"[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_4() { TestNotHandled( @"class C { void M() { var v = """" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_1() { TestNotHandled( @"class C { void M() { var v = $""""[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_2() { TestNotHandled( @"class C { void M() { var v = $"""" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_3() { TestNotHandled( @"class C { void M() { var v = $""""[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_4() { TestNotHandled( @"class C { void M() { var v = $"""" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInVerbatimString() { TestNotHandled( @"class C { void M() { var v = @""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolatedVerbatimString() { TestNotHandled( @"class C { void M() { var v = $@""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_BlockIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_NoneIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_BlockIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_NoneIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSimpleString1() { TestHandled( @"class C { void M() { var v = ""now is [||]the time""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the time""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString1() { TestHandled( @"class C { void M() { var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is "" + $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString2() { TestHandled( @"class C { void M() { var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the "" + $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString3() { TestHandled( @"class C { void M() { var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the { 1 + 2 }"" + $""[||] time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation1() { TestNotHandled( @"class C { void M() { var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation2() { TestNotHandled( @"class C { void M() { var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSelection() { TestNotHandled( @"class C { void M() { var v = ""now is [|the|] time""; } }"); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote1() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote2() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote3() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}"" + $""[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote4() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1[||]"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""[||]"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote5() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2[||]"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""[||]"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote6() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3[||]""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3"" + ""[||]""; } }", verifyUndo: false); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretSingleLine() { TestHandled( @"class C { void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretMultiLines() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretInterpolatedString() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var location = ""world""; var s = $""H[||]ello {location}!""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var location = ""world""; var s = $""H"" + $""[||]ello {location}!""; } }"); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled1() { TestHandled( @"class C { void M() { var s = ""Hello [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""[||]world""; } }", useTabs: true); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled2() { TestHandled( @"class C { void M() { var s = ""Hello "" + ""there [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""there "" + ""[||]world""; } }", useTabs: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions2; using IndentStyle = Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentStyle; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { [UseExportProvider] public class SplitStringLiteralCommandHandlerTests { /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestWorker( string inputMarkup, string expectedOutputMarkup, Action callback, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { using var workspace = TestWorkspace.CreateCSharp(inputMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(SmartIndent, LanguageNames.CSharp, indentStyle) .WithChangedOption(UseTabs, LanguageNames.CSharp, useTabs))); if (useTabs && expectedOutputMarkup != null) { Assert.Contains("\t", expectedOutputMarkup); } var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) { snapshotSpans.Add(selection.ToSnapshotSpan(originalSnapshot)); } view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitStringLiteralCommandHandler>(nameof(SplitStringLiteralCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.First().Start, view.Caret.Position.BufferPosition.Position); if (verifyUndo) { // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); Assert.Equal(originalSelections.First().Start, view.Caret.Position.BufferPosition.Position); } } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issure. This bug does not represent a product /// failure. /// </summary> private static void TestHandled( string inputMarkup, string expectedOutputMarkup, bool verifyUndo = true, IndentStyle indentStyle = IndentStyle.Smart, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, verifyUndo, indentStyle, useTabs); } private static void TestNotHandled(string inputMarkup) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }); Assert.True(notHandled); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeString() { TestNotHandled( @"class C { void M() { var v = [||]""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingBeforeInterpolatedString() { TestNotHandled( @"class C { void M() { var v = [||]$""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_1() { TestNotHandled( @"class C { void M() { var v = """"[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_2() { TestNotHandled( @"class C { void M() { var v = """" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_3() { TestNotHandled( @"class C { void M() { var v = """"[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterString_4() { TestNotHandled( @"class C { void M() { var v = """" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_1() { TestNotHandled( @"class C { void M() { var v = $""""[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_2() { TestNotHandled( @"class C { void M() { var v = $"""" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_3() { TestNotHandled( @"class C { void M() { var v = $""""[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingAfterInterpolatedString_4() { TestNotHandled( @"class C { void M() { var v = $"""" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInVerbatimString() { TestNotHandled( @"class C { void M() { var v = @""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolatedVerbatimString() { TestNotHandled( @"class C { void M() { var v = $@""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_BlockIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyString_NoneIndent() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }", verifyUndo: false, IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_BlockIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.Block); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInEmptyInterpolatedString_NoneIndent() { TestHandled( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }", indentStyle: IndentStyle.None); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSimpleString1() { TestHandled( @"class C { void M() { var v = ""now is [||]the time""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the time""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString1() { TestHandled( @"class C { void M() { var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is "" + $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString2() { TestHandled( @"class C { void M() { var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the "" + $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInterpolatedString3() { TestHandled( @"class C { void M() { var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the { 1 + 2 }"" + $""[||] time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation1() { TestNotHandled( @"class C { void M() { var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMissingInInterpolation2() { TestNotHandled( @"class C { void M() { var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestSelection() { TestNotHandled( @"class C { void M() { var v = ""now is [|the|] time""; } }"); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote1() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""[||]"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote2() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""[||]"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote3() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}"" + $""[||]""; var str2 = ""string1"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote4() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1[||]"" + ""string2"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""[||]"" + ""string2"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote5() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2[||]"" + ""string3""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""[||]"" + ""string3""; } }", verifyUndo: false); } [WorkItem(20258, "https://github.com/dotnet/roslyn/issues/20258")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestBeforeEndQuote6() { // Do not verifyUndo because of https://github.com/dotnet/roslyn/issues/28033 // When that issue is fixed, we can reenable verifyUndo TestHandled( @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3[||]""; } }", @"class Program { static void Main(string[] args) { var str = $""somestring { args[0]}"" + $""{args[1]}"" + $""{args[2]}""; var str2 = ""string1"" + ""string2"" + ""string3"" + ""[||]""; } }", verifyUndo: false); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretSingleLine() { TestHandled( @"class C { void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretMultiLines() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var v = ""now is [||]the ti[||]me""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var v = ""now is "" + ""[||]the ti"" + ""[||]me""; } }"); } [WorkItem(39040, "https://github.com/dotnet/roslyn/issues/39040")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestMultiCaretInterpolatedString() { TestHandled( @"class C { string s = ""hello w[||]orld""; void M() { var location = ""world""; var s = $""H[||]ello {location}!""; } }", @"class C { string s = ""hello w"" + ""[||]orld""; void M() { var location = ""world""; var s = $""H"" + $""[||]ello {location}!""; } }"); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled1() { TestHandled( @"class C { void M() { var s = ""Hello [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""[||]world""; } }", useTabs: true); } [WorkItem(40277, "https://github.com/dotnet/roslyn/issues/40277")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public void TestInStringWithKeepTabsEnabled2() { TestHandled( @"class C { void M() { var s = ""Hello "" + ""there [||]world""; } }", @"class C { void M() { var s = ""Hello "" + ""there "" + ""[||]world""; } }", useTabs: true); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { internal abstract class AbstractConverter : IConverter<ForEachStatementSyntax, StatementSyntax> { public ForEachInfo<ForEachStatementSyntax, StatementSyntax> ForEachInfo { get; } public AbstractConverter(ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => ForEachInfo = forEachInfo; public abstract void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); /// <summary> /// Creates a query expression or a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used into the last Select in the query expression or linq invocation.</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <param name="convertToQuery">Flag indicating if a query expression should be generated</param> /// <returns></returns> protected ExpressionSyntax CreateQueryExpressionOrLinqInvocation( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect, bool convertToQuery) { return convertToQuery ? CreateQueryExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect) : (ExpressionSyntax)CreateLinqInvocationOrSimpleExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect); } /// <summary> /// Creates a query expression. /// </summary> /// <param name="selectExpression">expression to be used into the last 'select ...' in the query expression</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private QueryExpressionSyntax CreateQueryExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) => SyntaxFactory.QueryExpression( CreateFromClause(ForEachInfo.ForEachStatement, ForEachInfo.LeadingTokens.GetTrivia(), Enumerable.Empty<SyntaxTrivia>()), SyntaxFactory.QueryBody( SyntaxFactory.List(ForEachInfo.ConvertingExtendedNodes.Select(node => CreateQueryClause(node))), SyntaxFactory.SelectClause(selectExpression) .WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)), continuation: null)) // The current coverage of foreach statements to support does not need to use query continuations. .WithAdditionalAnnotations(Formatter.Annotation); private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) { switch (node.Node.Kind()) { case SyntaxKind.VariableDeclarator: var variable = (VariableDeclaratorSyntax)node.Node; return SyntaxFactory.LetClause( SyntaxFactory.Token(SyntaxKind.LetKeyword), variable.Identifier, variable.Initializer.EqualsToken, variable.Initializer.Value) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.ForEachStatement: return CreateFromClause((ForEachStatementSyntax)node.Node, node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; return SyntaxFactory.WhereClause( SyntaxFactory.Token(SyntaxKind.WhereKeyword) .WithCommentsFrom(ifStatement.IfKeyword.LeadingTrivia, ifStatement.IfKeyword.TrailingTrivia), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); } throw ExceptionUtilities.Unreachable; } private static FromClauseSyntax CreateFromClause( ForEachStatementSyntax forEachStatement, IEnumerable<SyntaxTrivia> extraLeadingTrivia, IEnumerable<SyntaxTrivia> extraTrailingTrivia) => SyntaxFactory.FromClause( fromKeyword: SyntaxFactory.Token(SyntaxKind.FromKeyword) .WithCommentsFrom( forEachStatement.ForEachKeyword.LeadingTrivia, forEachStatement.ForEachKeyword.TrailingTrivia, forEachStatement.OpenParenToken) .KeepCommentsAndAddElasticMarkers(), type: forEachStatement.Type.IsVar ? null : forEachStatement.Type, identifier: forEachStatement.Type.IsVar ? forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false)) : forEachStatement.Identifier, inKeyword: forEachStatement.InKeyword.KeepCommentsAndAddElasticMarkers(), expression: forEachStatement.Expression) .WithCommentsFrom(extraLeadingTrivia, extraTrailingTrivia, forEachStatement.CloseParenToken); /// <summary> /// Creates a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used in the last 'Select' invocation</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) { var foreachStatement = ForEachInfo.ForEachStatement; selectExpression = selectExpression.WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)); var currentExtendedNodeIndex = 0; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: ForEachInfo.LeadingTokens.GetTrivia(), trailingCommentsTrivia: Enumerable.Empty<SyntaxTrivia>(), currentExtendedNodeIndex: ref currentExtendedNodeIndex) .WithAdditionalAnnotations(Formatter.Annotation); } private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ForEachStatementSyntax forEachStatement, ExpressionSyntax receiverForInvocation, IEnumerable<SyntaxTrivia> leadingCommentsTrivia, IEnumerable<SyntaxTrivia> trailingCommentsTrivia, ExpressionSyntax selectExpression, ref int currentExtendedNodeIndex) { leadingCommentsTrivia = forEachStatement.ForEachKeyword.GetAllTrivia().Concat(leadingCommentsTrivia); // Recursively create linq invocations, possibly updating the receiver (Where invocations), to get the inner expression for // the lambda body for the linq invocation to be created for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // if (n1 > n2) // yield return n1 + n2; // // OUTPUT: // c1.SelectMany(n1 => c2.Where(n2 => n1 > n2).Select(n2 => n1 + n2)) // var hasForEachChild = false; var lambdaBody = CreateLinqInvocationForExtendedNode(selectExpression, ref currentExtendedNodeIndex, ref receiverForInvocation, ref hasForEachChild); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false))), lambdaBody) .WithCommentsFrom(leadingCommentsTrivia, trailingCommentsTrivia, forEachStatement.OpenParenToken, forEachStatement.InKeyword, forEachStatement.CloseParenToken); // Create Select or SelectMany linq invocation for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // ... // // OUTPUT: // c1.Select(n1 => ... // OR // c1.SelectMany(n1 => ... // var invokedMethodName = !hasForEachChild ? nameof(Enumerable.Select) : nameof(Enumerable.SelectMany); // Avoid `.Select(x => x)` if (invokedMethodName == nameof(Enumerable.Select) && lambdaBody is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == forEachStatement.Identifier.ValueText) { // Because we're dropping the lambda, any comments associated with it need to be preserved. var droppedTrivia = new List<SyntaxTrivia>(); foreach (var token in lambda.DescendantTokens()) { droppedTrivia.AddRange(token.GetAllTrivia().Where(t => !t.IsWhitespace())); } return receiverForInvocation.WithAppendedTrailingTrivia(droppedTrivia); } return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiverForInvocation.Parenthesize(), SyntaxFactory.IdentifierName(invokedMethodName)), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); } /// <summary> /// Creates a linq invocation expression for the <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> node at the given index <paramref name="extendedNodeIndex"/> /// or returns the <paramref name="selectExpression"/> if all extended nodes have been processed. /// </summary> /// <param name="selectExpression">Innermost select expression</param> /// <param name="extendedNodeIndex">Index into <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> to be processed and updated.</param> /// <param name="receiver">Receiver for the generated linq invocation. Updated when processing an if statement.</param> /// <param name="hasForEachChild">Flag indicating if any of the processed <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> is a <see cref="ForEachStatementSyntax"/>.</param> private ExpressionSyntax CreateLinqInvocationForExtendedNode( ExpressionSyntax selectExpression, ref int extendedNodeIndex, ref ExpressionSyntax receiver, ref bool hasForEachChild) { // Check if we have converted all the descendant foreach/if statements. // If so, we return the select expression. if (extendedNodeIndex == ForEachInfo.ConvertingExtendedNodes.Length) { return selectExpression; } // Otherwise, convert the next foreach/if statement into a linq invocation. var node = ForEachInfo.ConvertingExtendedNodes[extendedNodeIndex]; switch (node.Node.Kind()) { // Nested ForEach statement is converted into a nested Select or SelectMany linq invocation. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // ... // // OUTPUT: // c1.SelectMany(n1 => c2.Select(n2 => ... // case SyntaxKind.ForEachStatement: hasForEachChild = true; var foreachStatement = (ForEachStatementSyntax)node.Node; ++extendedNodeIndex; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: node.ExtraLeadingComments, trailingCommentsTrivia: node.ExtraTrailingComments, currentExtendedNodeIndex: ref extendedNodeIndex); // Nested If statement is converted into a Where method invocation on the current receiver. For example: // // INPUT: // foreach (var n1 in c1) // if (n1 > 0) // ... // // OUTPUT: // c1.Where(n1 => n1 > 0).Select(n1 => ... // case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; var parentForEachStatement = ifStatement.GetAncestor<ForEachStatementSyntax>(); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(ifStatement.IfKeyword.GetAllTrivia().Concat(node.ExtraLeadingComments), node.ExtraTrailingComments); receiver = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiver.Parenthesize(), SyntaxFactory.IdentifierName(nameof(Enumerable.Where))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); ++extendedNodeIndex; return CreateLinqInvocationForExtendedNode(selectExpression, ref extendedNodeIndex, ref receiver, ref hasForEachChild); } 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. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { internal abstract class AbstractConverter : IConverter<ForEachStatementSyntax, StatementSyntax> { public ForEachInfo<ForEachStatementSyntax, StatementSyntax> ForEachInfo { get; } public AbstractConverter(ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => ForEachInfo = forEachInfo; public abstract void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); /// <summary> /// Creates a query expression or a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used into the last Select in the query expression or linq invocation.</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <param name="convertToQuery">Flag indicating if a query expression should be generated</param> /// <returns></returns> protected ExpressionSyntax CreateQueryExpressionOrLinqInvocation( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect, bool convertToQuery) { return convertToQuery ? CreateQueryExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect) : (ExpressionSyntax)CreateLinqInvocationOrSimpleExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect); } /// <summary> /// Creates a query expression. /// </summary> /// <param name="selectExpression">expression to be used into the last 'select ...' in the query expression</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private QueryExpressionSyntax CreateQueryExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) => SyntaxFactory.QueryExpression( CreateFromClause(ForEachInfo.ForEachStatement, ForEachInfo.LeadingTokens.GetTrivia(), Enumerable.Empty<SyntaxTrivia>()), SyntaxFactory.QueryBody( SyntaxFactory.List(ForEachInfo.ConvertingExtendedNodes.Select(node => CreateQueryClause(node))), SyntaxFactory.SelectClause(selectExpression) .WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)), continuation: null)) // The current coverage of foreach statements to support does not need to use query continuations. .WithAdditionalAnnotations(Formatter.Annotation); private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) { switch (node.Node.Kind()) { case SyntaxKind.VariableDeclarator: var variable = (VariableDeclaratorSyntax)node.Node; return SyntaxFactory.LetClause( SyntaxFactory.Token(SyntaxKind.LetKeyword), variable.Identifier, variable.Initializer.EqualsToken, variable.Initializer.Value) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.ForEachStatement: return CreateFromClause((ForEachStatementSyntax)node.Node, node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; return SyntaxFactory.WhereClause( SyntaxFactory.Token(SyntaxKind.WhereKeyword) .WithCommentsFrom(ifStatement.IfKeyword.LeadingTrivia, ifStatement.IfKeyword.TrailingTrivia), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); } throw ExceptionUtilities.Unreachable; } private static FromClauseSyntax CreateFromClause( ForEachStatementSyntax forEachStatement, IEnumerable<SyntaxTrivia> extraLeadingTrivia, IEnumerable<SyntaxTrivia> extraTrailingTrivia) => SyntaxFactory.FromClause( fromKeyword: SyntaxFactory.Token(SyntaxKind.FromKeyword) .WithCommentsFrom( forEachStatement.ForEachKeyword.LeadingTrivia, forEachStatement.ForEachKeyword.TrailingTrivia, forEachStatement.OpenParenToken) .KeepCommentsAndAddElasticMarkers(), type: forEachStatement.Type.IsVar ? null : forEachStatement.Type, identifier: forEachStatement.Type.IsVar ? forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false)) : forEachStatement.Identifier, inKeyword: forEachStatement.InKeyword.KeepCommentsAndAddElasticMarkers(), expression: forEachStatement.Expression) .WithCommentsFrom(extraLeadingTrivia, extraTrailingTrivia, forEachStatement.CloseParenToken); /// <summary> /// Creates a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used in the last 'Select' invocation</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) { var foreachStatement = ForEachInfo.ForEachStatement; selectExpression = selectExpression.WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)); var currentExtendedNodeIndex = 0; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: ForEachInfo.LeadingTokens.GetTrivia(), trailingCommentsTrivia: Enumerable.Empty<SyntaxTrivia>(), currentExtendedNodeIndex: ref currentExtendedNodeIndex) .WithAdditionalAnnotations(Formatter.Annotation); } private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ForEachStatementSyntax forEachStatement, ExpressionSyntax receiverForInvocation, IEnumerable<SyntaxTrivia> leadingCommentsTrivia, IEnumerable<SyntaxTrivia> trailingCommentsTrivia, ExpressionSyntax selectExpression, ref int currentExtendedNodeIndex) { leadingCommentsTrivia = forEachStatement.ForEachKeyword.GetAllTrivia().Concat(leadingCommentsTrivia); // Recursively create linq invocations, possibly updating the receiver (Where invocations), to get the inner expression for // the lambda body for the linq invocation to be created for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // if (n1 > n2) // yield return n1 + n2; // // OUTPUT: // c1.SelectMany(n1 => c2.Where(n2 => n1 > n2).Select(n2 => n1 + n2)) // var hasForEachChild = false; var lambdaBody = CreateLinqInvocationForExtendedNode(selectExpression, ref currentExtendedNodeIndex, ref receiverForInvocation, ref hasForEachChild); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false))), lambdaBody) .WithCommentsFrom(leadingCommentsTrivia, trailingCommentsTrivia, forEachStatement.OpenParenToken, forEachStatement.InKeyword, forEachStatement.CloseParenToken); // Create Select or SelectMany linq invocation for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // ... // // OUTPUT: // c1.Select(n1 => ... // OR // c1.SelectMany(n1 => ... // var invokedMethodName = !hasForEachChild ? nameof(Enumerable.Select) : nameof(Enumerable.SelectMany); // Avoid `.Select(x => x)` if (invokedMethodName == nameof(Enumerable.Select) && lambdaBody is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == forEachStatement.Identifier.ValueText) { // Because we're dropping the lambda, any comments associated with it need to be preserved. var droppedTrivia = new List<SyntaxTrivia>(); foreach (var token in lambda.DescendantTokens()) { droppedTrivia.AddRange(token.GetAllTrivia().Where(t => !t.IsWhitespace())); } return receiverForInvocation.WithAppendedTrailingTrivia(droppedTrivia); } return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiverForInvocation.Parenthesize(), SyntaxFactory.IdentifierName(invokedMethodName)), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); } /// <summary> /// Creates a linq invocation expression for the <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> node at the given index <paramref name="extendedNodeIndex"/> /// or returns the <paramref name="selectExpression"/> if all extended nodes have been processed. /// </summary> /// <param name="selectExpression">Innermost select expression</param> /// <param name="extendedNodeIndex">Index into <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> to be processed and updated.</param> /// <param name="receiver">Receiver for the generated linq invocation. Updated when processing an if statement.</param> /// <param name="hasForEachChild">Flag indicating if any of the processed <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> is a <see cref="ForEachStatementSyntax"/>.</param> private ExpressionSyntax CreateLinqInvocationForExtendedNode( ExpressionSyntax selectExpression, ref int extendedNodeIndex, ref ExpressionSyntax receiver, ref bool hasForEachChild) { // Check if we have converted all the descendant foreach/if statements. // If so, we return the select expression. if (extendedNodeIndex == ForEachInfo.ConvertingExtendedNodes.Length) { return selectExpression; } // Otherwise, convert the next foreach/if statement into a linq invocation. var node = ForEachInfo.ConvertingExtendedNodes[extendedNodeIndex]; switch (node.Node.Kind()) { // Nested ForEach statement is converted into a nested Select or SelectMany linq invocation. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // ... // // OUTPUT: // c1.SelectMany(n1 => c2.Select(n2 => ... // case SyntaxKind.ForEachStatement: hasForEachChild = true; var foreachStatement = (ForEachStatementSyntax)node.Node; ++extendedNodeIndex; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: node.ExtraLeadingComments, trailingCommentsTrivia: node.ExtraTrailingComments, currentExtendedNodeIndex: ref extendedNodeIndex); // Nested If statement is converted into a Where method invocation on the current receiver. For example: // // INPUT: // foreach (var n1 in c1) // if (n1 > 0) // ... // // OUTPUT: // c1.Where(n1 => n1 > 0).Select(n1 => ... // case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; var parentForEachStatement = ifStatement.GetAncestor<ForEachStatementSyntax>(); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(ifStatement.IfKeyword.GetAllTrivia().Concat(node.ExtraLeadingComments), node.ExtraTrailingComments); receiver = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiver.Parenthesize(), SyntaxFactory.IdentifierName(nameof(Enumerable.Where))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); ++extendedNodeIndex; return CreateLinqInvocationForExtendedNode(selectExpression, ref extendedNodeIndex, ref receiver, ref hasForEachChild); } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/Core/Portable/SourceGeneration/Nodes/PostInitOutputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class PostInitOutputNode : IIncrementalGeneratorOutputNode { private readonly Action<IncrementalGeneratorPostInitializationContext> _callback; public PostInitOutputNode(Action<IncrementalGeneratorPostInitializationContext> callback) { _callback = callback; } public IncrementalGeneratorOutputKind Kind => IncrementalGeneratorOutputKind.PostInit; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { _callback(new IncrementalGeneratorPostInitializationContext(context.Sources, cancellationToken)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class PostInitOutputNode : IIncrementalGeneratorOutputNode { private readonly Action<IncrementalGeneratorPostInitializationContext> _callback; public PostInitOutputNode(Action<IncrementalGeneratorPostInitializationContext> callback) { _callback = callback; } public IncrementalGeneratorOutputKind Kind => IncrementalGeneratorOutputKind.PostInit; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { _callback(new IncrementalGeneratorPostInitializationContext(context.Sources, cancellationToken)); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Interactive/HostTest/InteractiveHostDesktopTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostDesktopTests : AbstractInteractiveHostTests { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop64; internal override bool UseDefaultInitializationFile => false; [Fact] public async Task OutputRedirection() { await Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public async Task OutputRedirection2() { await Execute(@"System.Console.WriteLine(1);"); await Execute(@"System.Console.Error.WriteLine(2);"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); await Execute(@"System.Console.WriteLine(3);"); await Execute(@"System.Console.Error.WriteLine(4);"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/46414")] public async Task StackOverflow() { var process = Host.TryGetProcess(); await Execute(@" int goo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return goo(0,1,2,3,4,5,6,7,8,9) + goo(0,1,2,3,4,5,6,7,8,9); } goo(0,1,2,3,4,5,6,7,8,9) "); var output = await ReadOutputToEnd(); Assert.Equal("", output); // Hosting process exited with exit code ###. var errorOutput = (await ReadErrorOutputToEnd()).Trim(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "Process is terminated due to StackOverflowException.\n" + string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, process!.ExitCode), errorOutput); await Execute(@"1+1"); output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output.ToString()); } private const string MethodWithInfiniteLoop = @" void goo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public async Task AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); await RestartHost(); await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); var execution = await Execute(@"1+1"); var output = await ReadOutputToEnd(); Assert.True(execution); Assert.Equal("2\r\n", output); } [Fact(Skip = "529027")] public async Task AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error); Assert.True(mayTerminate.WaitOne()); // TODO: var service = _host.TryGetService(); // Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); // service!.EmulateClientExit(); // the process should terminate with exit code 0: process!.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public async Task AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); await Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); await RestartHost(); var execution = await Execute(@"1+1"); var output = await ReadOutputToEnd(); Assert.True(execution); Assert.Equal("2\r\n", output); } [Fact] public async Task AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1 1").Path; var task = await Host.ExecuteFileAsync(file); Assert.False(task.Success); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public async Task AsyncExecuteFile_NonExistingFile() { var result = await Host.ExecuteFileAsync("non existing file"); Assert.False(result.Success); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.Contains(InteractiveHostResources.Specified_file_not_found, errorOut, StringComparison.Ordinal); Assert.Contains(InteractiveHostResources.Searched_in_directory_colon, errorOut, StringComparison.Ordinal); } [Fact] public async Task AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Goo(int i) { return i; } } public int Goo(int i) { return i; } WriteLine(5); ").Path; var task = await Host.ExecuteFileAsync(file); var output = await ReadOutputToEnd(); Assert.True(task.Success); Assert.Equal("5", output.Trim()); await Execute("Goo(2)"); output = await ReadOutputToEnd(); Assert.Equal("2", output.Trim()); await Execute("new C().Goo(3)"); output = await ReadOutputToEnd(); Assert.Equal("3", output.Trim()); await Execute("new C().field"); output = await ReadOutputToEnd(); Assert.Equal("4", output.Trim()); } [Fact] public async Task AsyncExecuteFile_InvalidFileContent() { await Host.ExecuteFileAsync(typeof(Process).Assembly.Location); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public async Task AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); await Host.ExecuteFileAsync(file.Path); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public async Task UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); // TODO: _host.TryGetService()!.HookMaliciousAssemblyResolve(); Assert.True(mayTerminate.WaitOne()); await Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(await Execute(@"1+1")); var output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public async Task AddReference_Path() { var fxDir = await GetHostRuntimeDirectoryAsync(); Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference(Path.Combine(fxDir, "System.Data.dll"))); Assert.True(await Execute("new System.Data.DataSet()")); } [Fact] public async Task AddReference_PartialName() { Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference("System.Data")); Assert.True(await Execute("new System.Data.DataSet()")); } [Fact] public async Task AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(await LoadReference("System.Data")); Assert.True(await LoadReference("System")); Assert.True(await LoadReference("System.Xml")); await Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = await ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public async Task AddReference_FullName() { Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); Assert.True(await Execute("new System.Data.DataSet()")); } [ConditionalFact(typeof(Framework35Installed), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/5167")] public async Task AddReference_VersionUnification1() { // V3.5 unifies with the current Framework version: var result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); result = await LoadReference("System.Core"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); } // Caused by submission not inheriting references. [Fact(Skip = "101161")] public async Task AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: var output = await ReadOutputToEnd(); Assert.True(await LoadReference(c.Path)); Assert.True(await Execute("new C()")); Assert.Equal("C { }", output.Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = await Execute("new C()"); output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("C { }", output.Trim()); Assert.True(result); } #if TODO /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } #endif /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public async Task AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(await LoadReference(main.Path)); Assert.True(await Execute("Program.Main()")); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("1", output.Trim()); } [Fact] public async Task AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(await LoadReference(file1.Path)); Assert.True(await LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(await LoadReference(main.Path)); Assert.True(await Execute("Program.Main()")); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("2", output.Trim()); } [Fact] public async Task AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); await Execute("#r \"" + lib1.Path + "\""); await Execute("#r \"" + lib2.Path + "\""); await Execute("new C().M()"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("1", output); } [Fact(Skip = "101161")] public async Task AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: await Execute($@" #r ""{file.Path}"" C goo() => new C(); new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilation(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: await Execute($@" #r ""{file.Path}"" new D().Y "); // TODO: We should report an error that assembly named 'a' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal(@"1 2", output.Trim()); } [Fact(Skip = "129388")] public async Task AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilation(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); await Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); await Execute("new C1()"); await Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported". var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal(@"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", error.Trim()); Assert.Equal("", output.Trim()); } [Fact(Skip = "129388")] public async Task AddReference_MultipleReferencesWeakVersioning() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }"; var c2 = CreateCompilation(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); await Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); await Execute("new C1()"); await Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("TODO: error", error.Trim()); Assert.Equal("", output.Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public async Task ReferencePathsRsp() { var directory1 = Temp.CreateDirectory(); CompileLibrary(directory1, "Assembly0.dll", "Assembly0", @"public class C0 { }"); CompileLibrary(directory1, "Assembly1.dll", "Assembly1", @"public class C1 { }"); var initDirectory = Temp.CreateDirectory(); var initFile = initDirectory.CreateFile("init.csx"); initFile.WriteAllText(@" #r ""Assembly0.dll"" System.Console.WriteLine(typeof(C0).Assembly.GetName()); System.Console.WriteLine(typeof(C2).Assembly.GetName()); Print(ReferencePaths); "); var rspDirectory = Temp.CreateDirectory(); CompileLibrary(rspDirectory, "Assembly2.dll", "Assembly2", @"public class C2 { }"); CompileLibrary(rspDirectory, "Assembly3.dll", "Assembly3", @"public class C3 { }"); var rspFile = rspDirectory.CreateFile("init.rsp"); rspFile.WriteAllText($"/lib:{directory1.Path} /r:Assembly2.dll {initFile.Path}"); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var fxDir = await GetHostRuntimeDirectoryAsync(); await Execute(@" #r ""Assembly1.dll"" System.Console.WriteLine(typeof(C1).Assembly.GetName()); Print(ReferencePaths); "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); var expectedSearchPaths = PrintSearchPaths(fxDir, directory1.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" {string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path))} Assembly0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Assembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null {expectedSearchPaths} Assembly1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null {expectedSearchPaths} ", output); } [Fact] public async Task ReferencePathsRsp_Error() { var initDirectory = Temp.CreateDirectory(); var initFile = initDirectory.CreateFile("init.csx"); initFile.WriteAllText(@"#r ""Assembly.dll"""); var rspDirectory = Temp.CreateDirectory(); CompileLibrary(rspDirectory, "Assembly.dll", "Assembly", "public class C { }"); var rspFile = rspDirectory.CreateFile("init.rsp"); rspFile.WriteAllText($"{initFile.Path}"); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences( @$"{initFile.Path}(1,1): error CS0006: {string.Format(CSharpResources.ERR_NoMetadataFile, "Assembly.dll")}", error); } [Fact] public async Task DefaultUsings() { var rspFile = Temp.CreateFile(); rspFile.WriteAllText(@" /r:System /r:System.Core /r:Microsoft.CSharp /u:System /u:System.IO /u:System.Collections.Generic /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); await Execute(@" dynamic d = new ExpandoObject(); "); await Execute(@" Process p = new Process(); "); await Execute(@" Expression<Func<int>> e = () => 1; "); await Execute(@" var squares = from x in new[] { 1, 2, 3 } select x * x; "); await Execute(@" var sb = new StringBuilder(); "); await Execute(@" var list = new List<int>(); "); await Execute(@" var stream = new MemoryStream(); await Task.Delay(10); p = new Process(); Console.Write(""OK"") "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } OK ", output); } [Fact] public async Task InitialScript_Error() { var initFile = Temp.CreateFile(extension: ".csx").WriteAllText("1 1"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" /r:System /u:System.Diagnostics {initFile.Path} "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); await Execute("new Process()"); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@"{initFile.Path}(1,3): error CS1002: { CSharpResources.ERR_SemicolonExpected } ", error); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" { string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } [System.Diagnostics.Process] ", output); } [Fact] public async Task ScriptAndArguments() { var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" {scriptFile} a b c "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } ""a"" ""b"" ""c"" ", await ReadOutputToEnd()); } [Fact] public async Task Script_NoHostNamespaces() { await Execute("nameof(Microsoft.Missing)"); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@"(1,8): error CS0234: { string.Format(CSharpResources.ERR_DottedTypeNameNotFoundInNS, "Missing", "Microsoft") }", error); var output = await ReadOutputToEnd(); Assert.Equal("", output); } [Fact] public async Task ExecutesOnStaThread() { await Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public async Task ExecuteSequentially() { await Execute(@"using System; using System.Threading.Tasks;"); await Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); await Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); await Execute(@"3"); var output = await ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public async Task MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); await Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact, WorkItem(6457, "https://github.com/dotnet/roslyn/issues/6457")] public async Task MissingReferencesReuse() { var source = @" public class C { public System.Diagnostics.Process P; } "; var lib = CSharpCompilation.Create( "Lib", new[] { SyntaxFactory.ParseSyntaxTree(source) }, new[] { Net451.mscorlib, Net451.System }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var libFile = Temp.CreateFile("lib").WriteAllBytes(lib.EmitToArray()); await Execute($@"#r ""{libFile.Path}"""); await Execute("C c;"); await Execute("c = new C()"); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("C { P=null }", output); } [Fact, WorkItem(7280, "https://github.com/dotnet/roslyn/issues/7280")] public async Task AsyncContinueOnDifferentThread() { await Execute(@" using System; using System.Threading; using System.Threading.Tasks; Console.Write(Task.Run(() => { Thread.CurrentThread.Join(100); return 42; }).ContinueWith(t => t.Result).Result)"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("42", output); Assert.Empty(error); } [Fact] public async Task Exception() { await Execute(@"throw new System.Exception();"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", output); Assert.DoesNotContain("Unexpected", error, StringComparison.OrdinalIgnoreCase); Assert.True(error.StartsWith($"{new Exception().GetType()}: {new Exception().Message}")); } [Fact, WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException() { await Execute(@"int i = 100;"); await Execute(@"int j = 20; throw new System.Exception(""Bang!""); int k = 3;"); await Execute(@"i + j + k"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("120", output); AssertEx.AssertEqualToleratingWhitespaceDifferences("System.Exception: Bang!", error); } [Fact] public async Task Bitness() { await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd()); await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop32)); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd()); await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("4\r\n", await ReadOutputToEnd()); var result = await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Core)); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd()); await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd()); } #region Submission result printing - null/void/value. [Fact] public async Task SubmissionResult_PrintingNull() { await Execute(@" string s; s "); var output = await ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public async Task SubmissionResult_PrintingVoid() { await Execute(@"System.Console.WriteLine(2)"); var output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output); await Execute(@" void goo() { } goo() "); output = await ReadOutputToEnd(); Assert.Equal("", output); } // TODO (https://github.com/dotnet/roslyn/issues/7976): delete this [WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")] [Fact] public void Workaround7976() { Thread.Sleep(TimeSpan.FromSeconds(10)); } #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. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostDesktopTests : AbstractInteractiveHostTests { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop64; internal override bool UseDefaultInitializationFile => false; [Fact] public async Task OutputRedirection() { await Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public async Task OutputRedirection2() { await Execute(@"System.Console.WriteLine(1);"); await Execute(@"System.Console.Error.WriteLine(2);"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); await Execute(@"System.Console.WriteLine(3);"); await Execute(@"System.Console.Error.WriteLine(4);"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/46414")] public async Task StackOverflow() { var process = Host.TryGetProcess(); await Execute(@" int goo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return goo(0,1,2,3,4,5,6,7,8,9) + goo(0,1,2,3,4,5,6,7,8,9); } goo(0,1,2,3,4,5,6,7,8,9) "); var output = await ReadOutputToEnd(); Assert.Equal("", output); // Hosting process exited with exit code ###. var errorOutput = (await ReadErrorOutputToEnd()).Trim(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "Process is terminated due to StackOverflowException.\n" + string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, process!.ExitCode), errorOutput); await Execute(@"1+1"); output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output.ToString()); } private const string MethodWithInfiniteLoop = @" void goo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public async Task AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); await RestartHost(); await Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); var execution = await Execute(@"1+1"); var output = await ReadOutputToEnd(); Assert.True(execution); Assert.Equal("2\r\n", output); } [Fact(Skip = "529027")] public async Task AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error); Assert.True(mayTerminate.WaitOne()); // TODO: var service = _host.TryGetService(); // Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); // service!.EmulateClientExit(); // the process should terminate with exit code 0: process!.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public async Task AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); await Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); await RestartHost(); var execution = await Execute(@"1+1"); var output = await ReadOutputToEnd(); Assert.True(execution); Assert.Equal("2\r\n", output); } [Fact] public async Task AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1 1").Path; var task = await Host.ExecuteFileAsync(file); Assert.False(task.Success); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public async Task AsyncExecuteFile_NonExistingFile() { var result = await Host.ExecuteFileAsync("non existing file"); Assert.False(result.Success); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.Contains(InteractiveHostResources.Specified_file_not_found, errorOut, StringComparison.Ordinal); Assert.Contains(InteractiveHostResources.Searched_in_directory_colon, errorOut, StringComparison.Ordinal); } [Fact] public async Task AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Goo(int i) { return i; } } public int Goo(int i) { return i; } WriteLine(5); ").Path; var task = await Host.ExecuteFileAsync(file); var output = await ReadOutputToEnd(); Assert.True(task.Success); Assert.Equal("5", output.Trim()); await Execute("Goo(2)"); output = await ReadOutputToEnd(); Assert.Equal("2", output.Trim()); await Execute("new C().Goo(3)"); output = await ReadOutputToEnd(); Assert.Equal("3", output.Trim()); await Execute("new C().field"); output = await ReadOutputToEnd(); Assert.Equal("4", output.Trim()); } [Fact] public async Task AsyncExecuteFile_InvalidFileContent() { await Host.ExecuteFileAsync(typeof(Process).Assembly.Location); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public async Task AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); await Host.ExecuteFileAsync(file.Path); var errorOut = (await ReadErrorOutputToEnd()).Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public async Task UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); // TODO: _host.TryGetService()!.HookMaliciousAssemblyResolve(); Assert.True(mayTerminate.WaitOne()); await Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(await Execute(@"1+1")); var output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public async Task AddReference_Path() { var fxDir = await GetHostRuntimeDirectoryAsync(); Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference(Path.Combine(fxDir, "System.Data.dll"))); Assert.True(await Execute("new System.Data.DataSet()")); } [Fact] public async Task AddReference_PartialName() { Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference("System.Data")); Assert.True(await Execute("new System.Data.DataSet()")); } [Fact] public async Task AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(await LoadReference("System.Data")); Assert.True(await LoadReference("System")); Assert.True(await LoadReference("System.Xml")); await Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = await ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public async Task AddReference_FullName() { Assert.False(await Execute("new System.Data.DataSet()")); Assert.True(await LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); Assert.True(await Execute("new System.Data.DataSet()")); } [ConditionalFact(typeof(Framework35Installed), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/5167")] public async Task AddReference_VersionUnification1() { // V3.5 unifies with the current Framework version: var result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); result = await LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); result = await LoadReference("System.Core"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("", output.Trim()); Assert.True(result); } // Caused by submission not inheriting references. [Fact(Skip = "101161")] public async Task AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: var output = await ReadOutputToEnd(); Assert.True(await LoadReference(c.Path)); Assert.True(await Execute("new C()")); Assert.Equal("C { }", output.Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = await Execute("new C()"); output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("C { }", output.Trim()); Assert.True(result); } #if TODO /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } #endif /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public async Task AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(await LoadReference(main.Path)); Assert.True(await Execute("Program.Main()")); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("1", output.Trim()); } [Fact] public async Task AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(await LoadReference(file1.Path)); Assert.True(await LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(await LoadReference(main.Path)); Assert.True(await Execute("Program.Main()")); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal("2", output.Trim()); } [Fact] public async Task AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); await Execute("#r \"" + lib1.Path + "\""); await Execute("#r \"" + lib2.Path + "\""); await Execute("new C().M()"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("1", output); } [Fact(Skip = "101161")] public async Task AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: await Execute($@" #r ""{file.Path}"" C goo() => new C(); new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilation(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: await Execute($@" #r ""{file.Path}"" new D().Y "); // TODO: We should report an error that assembly named 'a' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error.Trim()); Assert.Equal(@"1 2", output.Trim()); } [Fact(Skip = "129388")] public async Task AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilation(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); await Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); await Execute("new C1()"); await Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported". var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal(@"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", error.Trim()); Assert.Equal("", output.Trim()); } [Fact(Skip = "129388")] public async Task AddReference_MultipleReferencesWeakVersioning() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }"; var c1 = CreateCompilation(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }"; var c2 = CreateCompilation(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); await Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); await Execute("new C1()"); await Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("TODO: error", error.Trim()); Assert.Equal("", output.Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public async Task ReferencePathsRsp() { var directory1 = Temp.CreateDirectory(); CompileLibrary(directory1, "Assembly0.dll", "Assembly0", @"public class C0 { }"); CompileLibrary(directory1, "Assembly1.dll", "Assembly1", @"public class C1 { }"); var initDirectory = Temp.CreateDirectory(); var initFile = initDirectory.CreateFile("init.csx"); initFile.WriteAllText(@" #r ""Assembly0.dll"" System.Console.WriteLine(typeof(C0).Assembly.GetName()); System.Console.WriteLine(typeof(C2).Assembly.GetName()); Print(ReferencePaths); "); var rspDirectory = Temp.CreateDirectory(); CompileLibrary(rspDirectory, "Assembly2.dll", "Assembly2", @"public class C2 { }"); CompileLibrary(rspDirectory, "Assembly3.dll", "Assembly3", @"public class C3 { }"); var rspFile = rspDirectory.CreateFile("init.rsp"); rspFile.WriteAllText($"/lib:{directory1.Path} /r:Assembly2.dll {initFile.Path}"); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var fxDir = await GetHostRuntimeDirectoryAsync(); await Execute(@" #r ""Assembly1.dll"" System.Console.WriteLine(typeof(C1).Assembly.GetName()); Print(ReferencePaths); "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); var expectedSearchPaths = PrintSearchPaths(fxDir, directory1.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" {string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path))} Assembly0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Assembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null {expectedSearchPaths} Assembly1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null {expectedSearchPaths} ", output); } [Fact] public async Task ReferencePathsRsp_Error() { var initDirectory = Temp.CreateDirectory(); var initFile = initDirectory.CreateFile("init.csx"); initFile.WriteAllText(@"#r ""Assembly.dll"""); var rspDirectory = Temp.CreateDirectory(); CompileLibrary(rspDirectory, "Assembly.dll", "Assembly", "public class C { }"); var rspFile = rspDirectory.CreateFile("init.rsp"); rspFile.WriteAllText($"{initFile.Path}"); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, culture: CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences( @$"{initFile.Path}(1,1): error CS0006: {string.Format(CSharpResources.ERR_NoMetadataFile, "Assembly.dll")}", error); } [Fact] public async Task DefaultUsings() { var rspFile = Temp.CreateFile(); rspFile.WriteAllText(@" /r:System /r:System.Core /r:Microsoft.CSharp /u:System /u:System.IO /u:System.Collections.Generic /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); await Execute(@" dynamic d = new ExpandoObject(); "); await Execute(@" Process p = new Process(); "); await Execute(@" Expression<Func<int>> e = () => 1; "); await Execute(@" var squares = from x in new[] { 1, 2, 3 } select x * x; "); await Execute(@" var sb = new StringBuilder(); "); await Execute(@" var list = new List<int>(); "); await Execute(@" var stream = new MemoryStream(); await Task.Delay(10); p = new Process(); Console.Write(""OK"") "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } OK ", output); } [Fact] public async Task InitialScript_Error() { var initFile = Temp.CreateFile(extension: ".csx").WriteAllText("1 1"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" /r:System /u:System.Diagnostics {initFile.Path} "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); await Execute("new Process()"); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@"{initFile.Path}(1,3): error CS1002: { CSharpResources.ERR_SemicolonExpected } ", error); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" { string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } [System.Diagnostics.Process] ", output); } [Fact] public async Task ScriptAndArguments() { var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" {scriptFile} a b c "); await Host.ResetAsync(new InteractiveHostOptions(Host.OptionsOpt!.HostPath, rspFile.Path, CultureInfo.InvariantCulture, Host.OptionsOpt!.Platform)); var error = await ReadErrorOutputToEnd(); Assert.Equal("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"{ string.Format(InteractiveHostResources.Loading_context_from_0, Path.GetFileName(rspFile.Path)) } ""a"" ""b"" ""c"" ", await ReadOutputToEnd()); } [Fact] public async Task Script_NoHostNamespaces() { await Execute("nameof(Microsoft.Missing)"); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@"(1,8): error CS0234: { string.Format(CSharpResources.ERR_DottedTypeNameNotFoundInNS, "Missing", "Microsoft") }", error); var output = await ReadOutputToEnd(); Assert.Equal("", output); } [Fact] public async Task ExecutesOnStaThread() { await Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public async Task ExecuteSequentially() { await Execute(@"using System; using System.Threading.Tasks;"); await Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); await Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); await Execute(@"3"); var output = await ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public async Task MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); await Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact, WorkItem(6457, "https://github.com/dotnet/roslyn/issues/6457")] public async Task MissingReferencesReuse() { var source = @" public class C { public System.Diagnostics.Process P; } "; var lib = CSharpCompilation.Create( "Lib", new[] { SyntaxFactory.ParseSyntaxTree(source) }, new[] { Net451.mscorlib, Net451.System }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var libFile = Temp.CreateFile("lib").WriteAllBytes(lib.EmitToArray()); await Execute($@"#r ""{libFile.Path}"""); await Execute("C c;"); await Execute("c = new C()"); var error = await ReadErrorOutputToEnd(); var output = await ReadOutputToEnd(); Assert.Equal("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("C { P=null }", output); } [Fact, WorkItem(7280, "https://github.com/dotnet/roslyn/issues/7280")] public async Task AsyncContinueOnDifferentThread() { await Execute(@" using System; using System.Threading; using System.Threading.Tasks; Console.Write(Task.Run(() => { Thread.CurrentThread.Join(100); return 42; }).ContinueWith(t => t.Result).Result)"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("42", output); Assert.Empty(error); } [Fact] public async Task Exception() { await Execute(@"throw new System.Exception();"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); Assert.Equal("", output); Assert.DoesNotContain("Unexpected", error, StringComparison.OrdinalIgnoreCase); Assert.True(error.StartsWith($"{new Exception().GetType()}: {new Exception().Message}")); } [Fact, WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException() { await Execute(@"int i = 100;"); await Execute(@"int j = 20; throw new System.Exception(""Bang!""); int k = 3;"); await Execute(@"i + j + k"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("120", output); AssertEx.AssertEqualToleratingWhitespaceDifferences("System.Exception: Bang!", error); } [Fact] public async Task Bitness() { await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd()); await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop32)); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd()); await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("4\r\n", await ReadOutputToEnd()); var result = await Host.ResetAsync(InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Core)); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadOutputToEnd()); await Host.ExecuteAsync(@"System.IntPtr.Size"); AssertEx.AssertEqualToleratingWhitespaceDifferences("", await ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences("8\r\n", await ReadOutputToEnd()); } #region Submission result printing - null/void/value. [Fact] public async Task SubmissionResult_PrintingNull() { await Execute(@" string s; s "); var output = await ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public async Task SubmissionResult_PrintingVoid() { await Execute(@"System.Console.WriteLine(2)"); var output = await ReadOutputToEnd(); Assert.Equal("2\r\n", output); await Execute(@" void goo() { } goo() "); output = await ReadOutputToEnd(); Assert.Equal("", output); } // TODO (https://github.com/dotnet/roslyn/issues/7976): delete this [WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")] [Fact] public void Workaround7976() { Thread.Sleep(TimeSpan.FromSeconds(10)); } #endregion } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicGenerateConstructorDialog.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicGenerateConstructorDialog : AbstractEditorTest { private const string DialogName = "PickMembersDialog"; protected override string LanguageName => LanguageNames.VisualBasic; public BasicGenerateConstructorDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicGenerateConstructorDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyCodeRefactoringOfferedAndCanceled() { SetUpEditor(@" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); Dialog_ClickCancel(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyCodeRefactoringOfferedAndAccepted() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(i As Integer, j As String, k As Boolean) Me.i = i Me.j = j Me.k = k End Sub End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyReordering() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.PressDialogButton(DialogName, "Down"); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(j As String, i As Integer, k As Boolean) Me.j = j Me.i = i Me.k = k End Sub End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyDeselect() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Space); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(j As String, k As Boolean) Me.j = j Me.k = k End Sub End Class", actualText); } private void VerifyDialog(bool isOpen) => VisualStudio.Editor.Verify.Dialog(DialogName, isOpen); private void Dialog_ClickCancel() => VisualStudio.Editor.PressDialogButton(DialogName, "CancelButton"); private void Dialog_ClickOk() => VisualStudio.Editor.PressDialogButton(DialogName, "OkButton"); } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicGenerateConstructorDialog : AbstractEditorTest { private const string DialogName = "PickMembersDialog"; protected override string LanguageName => LanguageNames.VisualBasic; public BasicGenerateConstructorDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicGenerateConstructorDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyCodeRefactoringOfferedAndCanceled() { SetUpEditor(@" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); Dialog_ClickCancel(); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyCodeRefactoringOfferedAndAccepted() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(i As Integer, j As String, k As Boolean) Me.i = i Me.j = j Me.k = k End Sub End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyReordering() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.PressDialogButton(DialogName, "Down"); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(j As String, i As Integer, k As Boolean) Me.j = j Me.i = i Me.k = k End Sub End Class", actualText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)] public void VerifyDeselect() { SetUpEditor( @" Class C Dim i as Integer Dim j as String Dim k as Boolean $$ End Class"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Generate constructor...", applyFix: true, blockUntilComplete: false); VerifyDialog(isOpen: true); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Tab); VisualStudio.Editor.DialogSendKeys(DialogName, VirtualKey.Space); Dialog_ClickOk(); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); var actualText = VisualStudio.Editor.GetText(); Assert.Contains( @" Class C Dim i as Integer Dim j as String Dim k as Boolean Public Sub New(j As String, k As Boolean) Me.j = j Me.k = k End Sub End Class", actualText); } private void VerifyDialog(bool isOpen) => VisualStudio.Editor.Verify.Dialog(DialogName, isOpen); private void Dialog_ClickCancel() => VisualStudio.Editor.PressDialogButton(DialogName, "CancelButton"); private void Dialog_ClickOk() => VisualStudio.Editor.PressDialogButton(DialogName, "OkButton"); } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/Organizing/Organizers/EventDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class EventDeclarationOrganizer : AbstractSyntaxNodeOrganizer<EventDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EventDeclarationOrganizer() { } protected override EventDeclarationSyntax Organize( EventDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.EventKeyword, syntax.Type, syntax.ExplicitInterfaceSpecifier, syntax.Identifier, syntax.AccessorList, syntax.SemicolonToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class EventDeclarationOrganizer : AbstractSyntaxNodeOrganizer<EventDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EventDeclarationOrganizer() { } protected override EventDeclarationSyntax Organize( EventDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.EventKeyword, syntax.Type, syntax.ExplicitInterfaceSpecifier, syntax.Identifier, syntax.AccessorList, syntax.SemicolonToken); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/EditorFeatures/Core/Implementation/BraceMatching/BraceMatchingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { [Export(typeof(IBraceMatchingService))] internal class BraceMatchingService : IBraceMatchingService { private readonly ImmutableArray<Lazy<IBraceMatcher, LanguageMetadata>> _braceMatchers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BraceMatchingService( [ImportMany] IEnumerable<Lazy<IBraceMatcher, LanguageMetadata>> braceMatchers) { _braceMatchers = braceMatchers.ToImmutableArray(); } public async Task<BraceMatchingResult?> GetMatchingBracesAsync(Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (position < 0 || position > text.Length) { throw new ArgumentException(nameof(position)); } var matchers = _braceMatchers.Where(b => b.Metadata.Language == document.Project.Language); foreach (var matcher in matchers) { cancellationToken.ThrowIfCancellationRequested(); var braces = await matcher.Value.FindBracesAsync(document, position, cancellationToken).ConfigureAwait(false); if (braces.HasValue) { return braces; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { [Export(typeof(IBraceMatchingService))] internal class BraceMatchingService : IBraceMatchingService { private readonly ImmutableArray<Lazy<IBraceMatcher, LanguageMetadata>> _braceMatchers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BraceMatchingService( [ImportMany] IEnumerable<Lazy<IBraceMatcher, LanguageMetadata>> braceMatchers) { _braceMatchers = braceMatchers.ToImmutableArray(); } public async Task<BraceMatchingResult?> GetMatchingBracesAsync(Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (position < 0 || position > text.Length) { throw new ArgumentException(nameof(position)); } var matchers = _braceMatchers.Where(b => b.Metadata.Language == document.Project.Language); foreach (var matcher in matchers) { cancellationToken.ThrowIfCancellationRequested(); var braces = await matcher.Value.FindBracesAsync(document, position, cancellationToken).ConfigureAwait(false); if (braces.HasValue) { return braces; } } return null; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/Core/Portable/InternalUtilities/StringExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal static class StringExtensions { private static ImmutableArray<string> s_lazyNumerals; internal static string GetNumeral(int number) { var numerals = s_lazyNumerals; if (numerals.IsDefault) { numerals = ImmutableArray.Create("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); ImmutableInterlocked.InterlockedInitialize(ref s_lazyNumerals, numerals); } Debug.Assert(number >= 0); return (number < numerals.Length) ? numerals[number] : number.ToString(); } public static string Join(this IEnumerable<string?> source, string separator) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return string.Join(separator, source); } public static bool LooksLikeInterfaceName(this string name) { return name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2]); } public static bool LooksLikeTypeParameterName(this string name) { return name.Length >= 3 && name[0] == 'T' && char.IsUpper(name[1]) && char.IsLower(name[2]); } private static readonly Func<char, char> s_toLower = char.ToLower; private static readonly Func<char, char> s_toUpper = char.ToUpper; [return: NotNullIfNotNull(parameterName: "shortName")] public static string? ToPascalCase( this string? shortName, bool trimLeadingTypePrefix = true) { return ConvertCase(shortName, trimLeadingTypePrefix, s_toUpper); } [return: NotNullIfNotNull(parameterName: "shortName")] public static string? ToCamelCase( this string? shortName, bool trimLeadingTypePrefix = true) { return ConvertCase(shortName, trimLeadingTypePrefix, s_toLower); } [return: NotNullIfNotNull(parameterName: "shortName")] private static string? ConvertCase( this string? shortName, bool trimLeadingTypePrefix, Func<char, char> convert) { // Special case the common .NET pattern of "IGoo" as a type name. In this case we // want to generate "goo" as the parameter name. if (!RoslynString.IsNullOrEmpty(shortName)) { if (trimLeadingTypePrefix && (shortName.LooksLikeInterfaceName() || shortName.LooksLikeTypeParameterName())) { return convert(shortName[1]) + shortName.Substring(2); } if (convert(shortName[0]) != shortName[0]) { return convert(shortName[0]) + shortName.Substring(1); } } return shortName; } internal static bool IsValidClrTypeName([NotNullWhen(returnValue: true)] this string? name) { return !RoslynString.IsNullOrEmpty(name) && name.IndexOf('\0') == -1; } /// <summary> /// Checks if the given name is a sequence of valid CLR names separated by a dot. /// </summary> internal static bool IsValidClrNamespaceName([NotNullWhen(returnValue: true)] this string? name) { if (RoslynString.IsNullOrEmpty(name)) { return false; } char lastChar = '.'; foreach (char c in name) { if (c == '\0' || (c == '.' && lastChar == '.')) { return false; } lastChar = c; } return lastChar != '.'; } private const string AttributeSuffix = "Attribute"; internal static string GetWithSingleAttributeSuffix( this string name, bool isCaseSensitive) { string? cleaned = name; while ((cleaned = GetWithoutAttributeSuffix(cleaned, isCaseSensitive)) != null) { name = cleaned; } return name + AttributeSuffix; } internal static bool TryGetWithoutAttributeSuffix( this string name, [NotNullWhen(returnValue: true)] out string? result) { return TryGetWithoutAttributeSuffix(name, isCaseSensitive: true, result: out result); } internal static string? GetWithoutAttributeSuffix( this string name, bool isCaseSensitive) { return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out var result) ? result : null; } internal static bool TryGetWithoutAttributeSuffix( this string name, bool isCaseSensitive, [NotNullWhen(returnValue: true)] out string? result) { if (name.HasAttributeSuffix(isCaseSensitive)) { result = name.Substring(0, name.Length - AttributeSuffix.Length); return true; } result = null; return false; } internal static bool HasAttributeSuffix(this string name, bool isCaseSensitive) { var comparison = isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; return name.Length > AttributeSuffix.Length && name.EndsWith(AttributeSuffix, comparison); } internal static bool IsValidUnicodeString(this string str) { int i = 0; while (i < str.Length) { char c = str[i++]; // (high surrogate, low surrogate) makes a valid pair, anything else is invalid: if (char.IsHighSurrogate(c)) { if (i < str.Length && char.IsLowSurrogate(str[i])) { i++; } else { // high surrogate not followed by low surrogate return false; } } else if (char.IsLowSurrogate(c)) { // previous character wasn't a high surrogate return false; } } return true; } /// <summary> /// Remove one set of leading and trailing double quote characters, if both are present. /// </summary> internal static string Unquote(this string arg) { return Unquote(arg, out _); } internal static string Unquote(this string arg, out bool quoted) { if (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"') { quoted = true; return arg.Substring(1, arg.Length - 2); } else { quoted = false; return arg; } } // String isn't IEnumerable<char> in the current Portable profile. internal static char First(this string arg) { return arg[0]; } // String isn't IEnumerable<char> in the current Portable profile. internal static char Last(this string arg) { return arg[arg.Length - 1]; } // String isn't IEnumerable<char> in the current Portable profile. internal static bool All(this string arg, Predicate<char> predicate) { foreach (char c in arg) { if (!predicate(c)) { return false; } } return true; } public static int GetCaseInsensitivePrefixLength(this string string1, string string2) { int x = 0; while (x < string1.Length && x < string2.Length && char.ToUpper(string1[x]) == char.ToUpper(string2[x])) { x++; } return x; } public static int GetCaseSensitivePrefixLength(this string string1, string string2) { int x = 0; while (x < string1.Length && x < string2.Length && string1[x] == string2[x]) { x++; } return x; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal static class StringExtensions { private static ImmutableArray<string> s_lazyNumerals; internal static string GetNumeral(int number) { var numerals = s_lazyNumerals; if (numerals.IsDefault) { numerals = ImmutableArray.Create("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); ImmutableInterlocked.InterlockedInitialize(ref s_lazyNumerals, numerals); } Debug.Assert(number >= 0); return (number < numerals.Length) ? numerals[number] : number.ToString(); } public static string Join(this IEnumerable<string?> source, string separator) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (separator == null) { throw new ArgumentNullException(nameof(separator)); } return string.Join(separator, source); } public static bool LooksLikeInterfaceName(this string name) { return name.Length >= 3 && name[0] == 'I' && char.IsUpper(name[1]) && char.IsLower(name[2]); } public static bool LooksLikeTypeParameterName(this string name) { return name.Length >= 3 && name[0] == 'T' && char.IsUpper(name[1]) && char.IsLower(name[2]); } private static readonly Func<char, char> s_toLower = char.ToLower; private static readonly Func<char, char> s_toUpper = char.ToUpper; [return: NotNullIfNotNull(parameterName: "shortName")] public static string? ToPascalCase( this string? shortName, bool trimLeadingTypePrefix = true) { return ConvertCase(shortName, trimLeadingTypePrefix, s_toUpper); } [return: NotNullIfNotNull(parameterName: "shortName")] public static string? ToCamelCase( this string? shortName, bool trimLeadingTypePrefix = true) { return ConvertCase(shortName, trimLeadingTypePrefix, s_toLower); } [return: NotNullIfNotNull(parameterName: "shortName")] private static string? ConvertCase( this string? shortName, bool trimLeadingTypePrefix, Func<char, char> convert) { // Special case the common .NET pattern of "IGoo" as a type name. In this case we // want to generate "goo" as the parameter name. if (!RoslynString.IsNullOrEmpty(shortName)) { if (trimLeadingTypePrefix && (shortName.LooksLikeInterfaceName() || shortName.LooksLikeTypeParameterName())) { return convert(shortName[1]) + shortName.Substring(2); } if (convert(shortName[0]) != shortName[0]) { return convert(shortName[0]) + shortName.Substring(1); } } return shortName; } internal static bool IsValidClrTypeName([NotNullWhen(returnValue: true)] this string? name) { return !RoslynString.IsNullOrEmpty(name) && name.IndexOf('\0') == -1; } /// <summary> /// Checks if the given name is a sequence of valid CLR names separated by a dot. /// </summary> internal static bool IsValidClrNamespaceName([NotNullWhen(returnValue: true)] this string? name) { if (RoslynString.IsNullOrEmpty(name)) { return false; } char lastChar = '.'; foreach (char c in name) { if (c == '\0' || (c == '.' && lastChar == '.')) { return false; } lastChar = c; } return lastChar != '.'; } private const string AttributeSuffix = "Attribute"; internal static string GetWithSingleAttributeSuffix( this string name, bool isCaseSensitive) { string? cleaned = name; while ((cleaned = GetWithoutAttributeSuffix(cleaned, isCaseSensitive)) != null) { name = cleaned; } return name + AttributeSuffix; } internal static bool TryGetWithoutAttributeSuffix( this string name, [NotNullWhen(returnValue: true)] out string? result) { return TryGetWithoutAttributeSuffix(name, isCaseSensitive: true, result: out result); } internal static string? GetWithoutAttributeSuffix( this string name, bool isCaseSensitive) { return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out var result) ? result : null; } internal static bool TryGetWithoutAttributeSuffix( this string name, bool isCaseSensitive, [NotNullWhen(returnValue: true)] out string? result) { if (name.HasAttributeSuffix(isCaseSensitive)) { result = name.Substring(0, name.Length - AttributeSuffix.Length); return true; } result = null; return false; } internal static bool HasAttributeSuffix(this string name, bool isCaseSensitive) { var comparison = isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; return name.Length > AttributeSuffix.Length && name.EndsWith(AttributeSuffix, comparison); } internal static bool IsValidUnicodeString(this string str) { int i = 0; while (i < str.Length) { char c = str[i++]; // (high surrogate, low surrogate) makes a valid pair, anything else is invalid: if (char.IsHighSurrogate(c)) { if (i < str.Length && char.IsLowSurrogate(str[i])) { i++; } else { // high surrogate not followed by low surrogate return false; } } else if (char.IsLowSurrogate(c)) { // previous character wasn't a high surrogate return false; } } return true; } /// <summary> /// Remove one set of leading and trailing double quote characters, if both are present. /// </summary> internal static string Unquote(this string arg) { return Unquote(arg, out _); } internal static string Unquote(this string arg, out bool quoted) { if (arg.Length > 1 && arg[0] == '"' && arg[arg.Length - 1] == '"') { quoted = true; return arg.Substring(1, arg.Length - 2); } else { quoted = false; return arg; } } // String isn't IEnumerable<char> in the current Portable profile. internal static char First(this string arg) { return arg[0]; } // String isn't IEnumerable<char> in the current Portable profile. internal static char Last(this string arg) { return arg[arg.Length - 1]; } // String isn't IEnumerable<char> in the current Portable profile. internal static bool All(this string arg, Predicate<char> predicate) { foreach (char c in arg) { if (!predicate(c)) { return false; } } return true; } public static int GetCaseInsensitivePrefixLength(this string string1, string string2) { int x = 0; while (x < string1.Length && x < string2.Length && char.ToUpper(string1[x]) == char.ToUpper(string2[x])) { x++; } return x; } public static int GetCaseSensitivePrefixLength(this string string1, string string2) { int x = 0; while (x < string1.Length && x < string2.Length && string1[x] == string2[x]) { x++; } return x; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/Core/Portable/CodeFixes/Configuration/ConfigurationUpdater.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration { /// <summary> /// Helper class to configure diagnostic severity or code style option value based on .editorconfig file /// </summary> internal sealed partial class ConfigurationUpdater { private enum ConfigurationKind { OptionValue, Severity, BulkConfigure } private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; private const string BulkConfigureAllAnalyzerDiagnosticsOptionKey = "dotnet_analyzer_diagnostic.severity"; private const string BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix = "dotnet_analyzer_diagnostic.category-"; private const string AllAnalyzerDiagnosticsCategory = ""; // Regular expression for .editorconfig header. // For example: "[*.cs] # Optional comment" // "[*.{vb,cs}]" // "[*] ; Optional comment" // "[ConsoleApp/Program.cs]" private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); // Regular expression for .editorconfig code style option entry. // For example: // 1. "dotnet_style_object_initializer = true # Optional comment" // 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment" // 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment" // 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment" // 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment" // // Regex groups: // 1. Option key // 2. Option value // 3. Optional severity suffix in option value, i.e. ':severity' suffix // 4. Optional comment suffix private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private readonly string? _optionNameOpt; private readonly string? _newOptionValueOpt; private readonly string _newSeverity; private readonly ConfigurationKind _configurationKind; private readonly Diagnostic? _diagnostic; private readonly string? _categoryToBulkConfigure; private readonly bool _isPerLanguage; private readonly Project _project; private readonly CancellationToken _cancellationToken; private readonly bool _addNewEntryIfNoExistingEntryFound; private readonly string _language; private ConfigurationUpdater( string? optionNameOpt, string? newOptionValueOpt, string newSeverity, ConfigurationKind configurationKind, Diagnostic? diagnosticToConfigure, string? categoryToBulkConfigure, bool isPerLanguage, Project project, bool addNewEntryIfNoExistingEntryFound, CancellationToken cancellationToken) { Debug.Assert(configurationKind != ConfigurationKind.OptionValue || !string.IsNullOrEmpty(newOptionValueOpt)); Debug.Assert(!string.IsNullOrEmpty(newSeverity)); Debug.Assert(diagnosticToConfigure != null ^ categoryToBulkConfigure != null); Debug.Assert((categoryToBulkConfigure != null) == (configurationKind == ConfigurationKind.BulkConfigure)); _optionNameOpt = optionNameOpt; _newOptionValueOpt = newOptionValueOpt; _newSeverity = newSeverity; _configurationKind = configurationKind; _diagnostic = diagnosticToConfigure; _categoryToBulkConfigure = categoryToBulkConfigure; _isPerLanguage = isPerLanguage; _project = project; _cancellationToken = cancellationToken; _addNewEntryIfNoExistingEntryFound = addNewEntryIfNoExistingEntryFound; _language = project.Language; } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the severity of the given <paramref name="diagnostic"/> is configured to be the given /// <paramref name="severity"/>. /// </summary> public static Task<Solution> ConfigureSeverityAsync( ReportDiagnostic severity, Diagnostic diagnostic, Project project, CancellationToken cancellationToken) { if (severity == ReportDiagnostic.Default) { severity = diagnostic.DefaultSeverity.ToReportDiagnostic(); } return ConfigureSeverityAsync(severity.ToEditorConfigString(), diagnostic, project, cancellationToken); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the severity of the given <paramref name="diagnostic"/> is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> ConfigureSeverityAsync( string editorConfigSeverity, Diagnostic diagnostic, Project project, CancellationToken cancellationToken) { // For option based code style diagnostic, try to find the .editorconfig key-value pair for the // option setting. var codeStyleOptionValues = GetCodeStyleOptionValuesForDiagnostic(diagnostic, project); ConfigurationUpdater updater; if (!codeStyleOptionValues.IsEmpty) { return ConfigureCodeStyleOptionsAsync( codeStyleOptionValues.Select(t => (t.optionName, t.currentOptionValue, t.isPerLanguage)), editorConfigSeverity, diagnostic, project, configurationKind: ConfigurationKind.Severity, cancellationToken); } else { updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.Severity, diagnostic, categoryToBulkConfigure: null, isPerLanguage: false, project, addNewEntryIfNoExistingEntryFound: true, cancellationToken); return updater.ConfigureAsync(); } } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the default severity of the diagnostics with the given <paramref name="category"/> is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> BulkConfigureSeverityAsync( string editorConfigSeverity, string category, Project project, CancellationToken cancellationToken) { Contract.ThrowIfFalse(!string.IsNullOrEmpty(category)); return BulkConfigureSeverityCoreAsync(editorConfigSeverity, category, project, cancellationToken); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the default severity of all diagnostics is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> BulkConfigureSeverityAsync( string editorConfigSeverity, Project project, CancellationToken cancellationToken) { return BulkConfigureSeverityCoreAsync(editorConfigSeverity, category: AllAnalyzerDiagnosticsCategory, project, cancellationToken); } private static Task<Solution> BulkConfigureSeverityCoreAsync( string editorConfigSeverity, string category, Project project, CancellationToken cancellationToken) { Contract.ThrowIfNull(category); var updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.BulkConfigure, diagnosticToConfigure: null, category, isPerLanguage: false, project, addNewEntryIfNoExistingEntryFound: true, cancellationToken); return updater.ConfigureAsync(); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the given <paramref name="optionName"/> is configured to have the given <paramref name="optionValue"/>. /// </summary> public static Task<Solution> ConfigureCodeStyleOptionAsync( string optionName, string optionValue, Diagnostic diagnostic, bool isPerLanguage, Project project, CancellationToken cancellationToken) => ConfigureCodeStyleOptionsAsync( SpecializedCollections.SingletonEnumerable((optionName, optionValue, isPerLanguage)), diagnostic.Severity.ToEditorConfigString(), diagnostic, project, configurationKind: ConfigurationKind.OptionValue, cancellationToken); private static async Task<Solution> ConfigureCodeStyleOptionsAsync( IEnumerable<(string optionName, string optionValue, bool isPerLanguage)> codeStyleOptionValues, string editorConfigSeverity, Diagnostic diagnostic, Project project, ConfigurationKind configurationKind, CancellationToken cancellationToken) { Debug.Assert(!codeStyleOptionValues.IsEmpty()); // For severity configuration for IDE code style diagnostics, we want to ensure the following: // 1. For code style option based entries, i.e. "%option_name% = %option_value%:%severity%, // we only update existing entries, but do not add a new entry. // 2. For "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity%" entries, we update existing entries, and if none found // we add a single new severity configuration entry for all code style options that share the same diagnostic ID. // This behavior is required to ensure that we always add the up-to-date dotnet_diagnostic based severity entry // so the IDE code style diagnostics can be enforced in build, as the compiler only understands dotnet_diagnostic entries. // See https://github.com/dotnet/roslyn/issues/44201 for more details. // First handle "%option_name% = %option_value%:%severity% entries. // For option value configuration, we always want to add new entry if no existing value is found. // For severity configuration, we only want to update existing value if found. var currentProject = project; var areAllOptionsPerLanguage = true; var addNewEntryIfNoExistingEntryFound = configurationKind != ConfigurationKind.Severity; foreach (var (optionName, optionValue, isPerLanguage) in codeStyleOptionValues) { Debug.Assert(!string.IsNullOrEmpty(optionName)); Debug.Assert(optionValue != null); var updater = new ConfigurationUpdater(optionName, optionValue, editorConfigSeverity, configurationKind, diagnostic, categoryToBulkConfigure: null, isPerLanguage, currentProject, addNewEntryIfNoExistingEntryFound, cancellationToken); var solution = await updater.ConfigureAsync().ConfigureAwait(false); currentProject = solution.GetProject(project.Id)!; areAllOptionsPerLanguage = areAllOptionsPerLanguage && isPerLanguage; } // For severity configuration, handle "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity%" entry. // We want to update existing entry + add new entry if no existing value is found. if (configurationKind == ConfigurationKind.Severity) { var updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.Severity, diagnostic, categoryToBulkConfigure: null, isPerLanguage: areAllOptionsPerLanguage, currentProject, addNewEntryIfNoExistingEntryFound: true, cancellationToken); var solution = await updater.ConfigureAsync().ConfigureAwait(false); currentProject = solution.GetProject(project.Id)!; } return currentProject.Solution; } private async Task<Solution> ConfigureAsync() { // Find existing .editorconfig or generate a new one if none exists. var editorConfigDocument = FindOrGenerateEditorConfig(); if (editorConfigDocument == null) { return _project.Solution; } var solution = editorConfigDocument.Project.Solution; var originalText = await editorConfigDocument.GetTextAsync(_cancellationToken).ConfigureAwait(false); // Compute the updated text for analyzer config document. var newText = GetNewAnalyzerConfigDocumentText(originalText, editorConfigDocument); if (newText == null || newText.Equals(originalText)) { return solution; } // Add the newly added analyzer config document as a solution item. // The analyzer config document is not yet created, so we just mark the file // path for tracking and add it as a solution item whenever the file gets created by the code fix application. var service = _project.Solution.Workspace.Services.GetService<IAddSolutionItemService>(); service?.TrackFilePathAndAddSolutionItemWhenFileCreated(editorConfigDocument.FilePath); return solution.WithAnalyzerConfigDocumentText(editorConfigDocument.Id, newText); } private AnalyzerConfigDocument? FindOrGenerateEditorConfig() { var analyzerConfigPath = _diagnostic != null ? _project.TryGetAnalyzerConfigPathForDiagnosticConfiguration(_diagnostic) : _project.TryGetAnalyzerConfigPathForProjectConfiguration(); if (analyzerConfigPath == null) { return null; } if (_project.Solution?.FilePath == null) { // Project has no solution or solution without a file path. // Add analyzer config to just the current project. return _project.GetOrCreateAnalyzerConfigDocument(analyzerConfigPath); } // Otherwise, add analyzer config document to all applicable projects for the current project's solution. AnalyzerConfigDocument? analyzerConfigDocument = null; var analyzerConfigDirectory = PathUtilities.GetDirectoryName(analyzerConfigPath) ?? throw ExceptionUtilities.Unreachable; var currentSolution = _project.Solution; foreach (var projectId in _project.Solution.ProjectIds) { var project = currentSolution.GetProject(projectId); if (project?.FilePath?.StartsWith(analyzerConfigDirectory) == true) { var addedAnalyzerConfigDocument = project.GetOrCreateAnalyzerConfigDocument(analyzerConfigPath); if (addedAnalyzerConfigDocument != null) { analyzerConfigDocument ??= addedAnalyzerConfigDocument; currentSolution = addedAnalyzerConfigDocument.Project.Solution; } } } return analyzerConfigDocument; } private static ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)> GetCodeStyleOptionValuesForDiagnostic( Diagnostic diagnostic, Project project) { // For option based code style diagnostic, try to find the .editorconfig key-value pair for the // option setting. // For example, IDE diagnostics which are configurable with following code style option based .editorconfig entry: // "%option_name% = %option_value%:%severity% // we return '(option_name, new_option_value, new_severity)' var codeStyleOptions = GetCodeStyleOptionsForDiagnostic(diagnostic, project); if (!codeStyleOptions.IsEmpty) { var optionSet = project.Solution.Workspace.Options; var builder = ArrayBuilder<(string optionName, string currentOptionValue, bool isPerLanguage)>.GetInstance(); try { foreach (var (_, codeStyleOption, editorConfigLocation, isPerLanguage) in codeStyleOptions) { if (!TryGetEditorConfigStringParts(codeStyleOption, editorConfigLocation, optionSet, out var parts)) { // Did not find a match, bail out. return ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)>.Empty; } builder.Add((parts.optionName, parts.optionValue, isPerLanguage)); } return builder.ToImmutable(); } finally { builder.Free(); } } return ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)>.Empty; } internal static bool TryGetEditorConfigStringParts( ICodeStyleOption codeStyleOption, IEditorConfigStorageLocation2 editorConfigLocation, OptionSet optionSet, out (string optionName, string optionValue) parts) { var editorConfigString = editorConfigLocation.GetEditorConfigString(codeStyleOption, optionSet); if (!string.IsNullOrEmpty(editorConfigString)) { var match = s_optionEntryPattern.Match(editorConfigString); if (match.Success) { parts = (optionName: match.Groups[1].Value.Trim(), optionValue: match.Groups[2].Value.Trim()); return true; } } parts = default; return false; } internal static ImmutableArray<(OptionKey optionKey, ICodeStyleOption codeStyleOptionValue, IEditorConfigStorageLocation2 location, bool isPerLanguage)> GetCodeStyleOptionsForDiagnostic( Diagnostic diagnostic, Project project) { if (IDEDiagnosticIdToOptionMappingHelper.TryGetMappedOptions(diagnostic.Id, project.Language, out var options)) { var optionSet = project.Solution.Workspace.Options; using var _ = ArrayBuilder<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.GetInstance(out var builder); foreach (var option in options.OrderBy(option => option.Name)) { var editorConfigLocation = option.StorageLocations.OfType<IEditorConfigStorageLocation2>().FirstOrDefault(); if (editorConfigLocation != null) { var optionKey = new OptionKey(option, option.IsPerLanguage ? project.Language : null); if (optionSet.GetOption(optionKey) is ICodeStyleOption codeStyleOption) { builder.Add((optionKey, codeStyleOption, editorConfigLocation, option.IsPerLanguage)); continue; } } // Did not find a match. return ImmutableArray<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.Empty; } return builder.ToImmutable(); } return ImmutableArray<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.Empty; } private SourceText? GetNewAnalyzerConfigDocumentText(SourceText originalText, AnalyzerConfigDocument editorConfigDocument) { // Check if an entry to configure the rule severity already exists in the .editorconfig file. // If it does, we update the existing entry with the new severity. var (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = CheckIfRuleExistsAndReplaceInFile(originalText, editorConfigDocument); if (newText != null) { return newText; } if (!_addNewEntryIfNoExistingEntryFound) { return originalText; } // We did not find any existing entry in the in the .editorconfig file to configure rule severity. // So we add a new configuration entry to the .editorconfig file. return AddMissingRule(originalText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } private (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) CheckIfRuleExistsAndReplaceInFile( SourceText result, AnalyzerConfigDocument editorConfigDocument) { // If there's an error finding the editorconfig directory, bail out. var editorConfigDirectory = PathUtilities.GetDirectoryName(editorConfigDocument.FilePath); if (editorConfigDirectory == null) { return (null, null, null); } var relativePath = string.Empty; var diagnosticFilePath = string.Empty; // If diagnostic SourceTree is null, it means either Location.None or Bulk configuration at root editorconfig, and thus no relative path. var diagnosticSourceTree = _diagnostic?.Location.SourceTree; if (diagnosticSourceTree != null) { // Finds the relative path between editorconfig directory and diagnostic filepath. diagnosticFilePath = diagnosticSourceTree.FilePath.ToLowerInvariant(); relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), diagnosticFilePath); relativePath = PathUtilities.NormalizeWithForwardSlash(relativePath); } TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in result.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; // Regex groups: // 1. Option key // 2. Option value // 3. Optional severity suffix, i.e. ':severity' suffix // 4. Optional comment suffix var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); // Verify the most recent header is a valid header if (mostRecentHeader != null && lastValidHeader != null && mostRecentHeader.Equals(lastValidHeader)) { // We found the rule in the file -- replace it with updated option value/severity. if (key.Equals(_optionNameOpt)) { // We found an option configuration entry of form: // "%option_name% = %option_value% // OR // "%option_name% = %option_value%:%severity% var newOptionValue = _configurationKind == ConfigurationKind.OptionValue ? $"{value.GetLeadingWhitespace()}{_newOptionValueOpt}{value.GetTrailingWhitespace()}" : value; var newSeverityValue = _configurationKind == ConfigurationKind.Severity && severitySuffixInValue.Length > 0 ? $":{_newSeverity}" : severitySuffixInValue; textChange = new TextChange(curLine.Span, $"{untrimmedKey}={newOptionValue}{newSeverityValue}{commentValue}"); } else { // We want to detect severity based entry only when we are configuring severity and have no option name specified. if (_configurationKind != ConfigurationKind.OptionValue && _optionNameOpt == null && severitySuffixInValue.Length == 0 && key.EndsWith(SeveritySuffix)) { // We found a rule configuration entry of severity based form: // "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity% // OR // "dotnet_analyzer_diagnostic.severity = %severity% // OR // "dotnet_analyzer_diagnostic.category-<%DiagnosticCategory%>.severity = %severity% var foundMatch = false; switch (_configurationKind) { case ConfigurationKind.Severity: RoslynDebug.Assert(_diagnostic != null); if (key.StartsWith(DiagnosticOptionPrefix, StringComparison.Ordinal)) { var diagIdLength = key.Length - (DiagnosticOptionPrefix.Length + SeveritySuffix.Length); if (diagIdLength > 0) { var diagId = key.Substring(DiagnosticOptionPrefix.Length, diagIdLength); foundMatch = string.Equals(diagId, _diagnostic.Id, StringComparison.OrdinalIgnoreCase); } } break; case ConfigurationKind.BulkConfigure: RoslynDebug.Assert(_categoryToBulkConfigure != null); if (_categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory) { foundMatch = key == BulkConfigureAllAnalyzerDiagnosticsOptionKey; } else { if (key.StartsWith(BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix, StringComparison.Ordinal)) { var categoryLength = key.Length - (BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix.Length + SeveritySuffix.Length); var category = key.Substring(BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix.Length, categoryLength); foundMatch = string.Equals(category, _categoryToBulkConfigure, StringComparison.OrdinalIgnoreCase); } } break; } if (foundMatch) { var newSeverityValue = $"{value.GetLeadingWhitespace()}{_newSeverity}{value.GetTrailingWhitespace()}"; textChange = new TextChange(curLine.Span, $"{untrimmedKey}={newSeverityValue}{commentValue}"); } } } } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { // We found a header entry such as '[*.cs]', '[*.vb]', etc. // Verify that header is valid. mostRecentHeader = curLine; var groups = s_headerPattern.Match(curLineText.Trim()).Groups; var mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); if (mostRecentHeaderText.Equals("*")) { lastValidHeader = mostRecentHeader; } else { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); // Creating the header regex string, ex. [*.{cs,vb}] => ((\.cs)|(\.vb)) var headerRegexStr = fileName + @"((\." + splicedFileExtensions[0] + ")"; for (var i = 1; i < splicedFileExtensions.Length; i++) { headerRegexStr += @"|(\." + splicedFileExtensions[i] + ")"; } headerRegexStr += ")"; var headerRegex = new Regex(headerRegexStr); // We check that the relative path of the .editorconfig file to the diagnostic file // matches the header regex pattern. if (headerRegex.IsMatch(relativePath)) { var match = headerRegex.Match(relativePath).Value; var matchWithoutExtension = match.Substring(0, match.LastIndexOf('.')); // Edge case: The below statement checks that we correctly handle cases such as a header of [m.cs] and // a file name of Program.cs. if (matchWithoutExtension.Contains(PathUtilities.GetFileName(diagnosticFilePath, false))) { // If the diagnostic's isPerLanguage = true, the rule is valid for both C# and VB. // For the purpose of adding missing rules later, we want to keep track of whether there is a // valid header that contains both [*.cs] and [*.vb]. // If isPerLanguage = false or a compiler diagnostic, the rule is only valid for one of the languages. // Thus, we want to keep track of whether there is an existing header that only contains [*.cs] or only // [*.vb], depending on the language. // We also keep track of the last valid header for the language. var isLanguageAgnosticEntry = (_diagnostic == null || !SuppressionHelpers.IsCompilerDiagnostic(_diagnostic)) && _isPerLanguage; if (isLanguageAgnosticEntry) { if ((_language.Equals(LanguageNames.CSharp) || _language.Equals(LanguageNames.VisualBasic)) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Contains("vb")) { lastValidSpecificHeader = mostRecentHeader; } } else if (splicedFileExtensions.Length == 1) { if (_language.Equals(LanguageNames.CSharp) && splicedFileExtensions.Contains("cs")) { lastValidSpecificHeader = mostRecentHeader; } else if (_language.Equals(LanguageNames.VisualBasic) && splicedFileExtensions.Contains("vb")) { lastValidSpecificHeader = mostRecentHeader; } } lastValidHeader = mostRecentHeader; } } // Location.None special case. else if (relativePath.IsEmpty() && new Regex(fileName).IsMatch(relativePath)) { if ((_language.Equals(LanguageNames.CSharp) && splicedFileExtensions.Contains("cs")) || (_language.Equals(LanguageNames.VisualBasic) && splicedFileExtensions.Contains("vb"))) { lastValidHeader = mostRecentHeader; } } } } // We want to keep track of how far this (valid) section spans. if (mostRecentHeader != null && lastValidHeader != null && mostRecentHeader.Equals(lastValidHeader)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (result.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } private SourceText? AddMissingRule( SourceText result, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) { // Create a new rule configuration entry for the given diagnostic ID or bulk configuration category. // If optionNameOpt and optionValueOpt are non-null, it indicates an option based diagnostic ID // which can be configured by a new entry such as: "%option_name% = %option_value%:%severity% // Otherwise, if diagnostic is non-null, it indicates a non-option diagnostic ID, // which can be configured by a new entry such as: "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity% // Otherwise, it indicates a bulk configuration entry for default severity of a specific diagnostic category or all analyzer diagnostics, // which can be configured by a new entry such as: // 1. All analyzer diagnostics: "dotnet_analyzer_diagnostic.severity = %severity% // 2. Category configuration: "dotnet_analyzer_diagnostic.category-<%DiagnosticCategory%>.severity = %severity% var newEntry = !string.IsNullOrEmpty(_optionNameOpt) && !string.IsNullOrEmpty(_newOptionValueOpt) ? $"{_optionNameOpt} = {_newOptionValueOpt}" : _diagnostic != null ? $"{DiagnosticOptionPrefix}{_diagnostic.Id}{SeveritySuffix} = {_newSeverity}" : _categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory ? $"{BulkConfigureAllAnalyzerDiagnosticsOptionKey} = {_newSeverity}" : $"{BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix}{_categoryToBulkConfigure}{SeveritySuffix} = {_newSeverity}"; // Insert a new line and comment text above the new entry var commentPrefix = _diagnostic != null ? $"{_diagnostic.Id}: {_diagnostic.Descriptor.Title}" : _categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory ? "Default severity for all analyzer diagnostics" : $"Default severity for analyzer diagnostics with category '{_categoryToBulkConfigure}'"; newEntry = $"\r\n# {commentPrefix}\r\n{newEntry}\r\n"; // Check if have a correct existing header for the new entry. // - If the diagnostic's isPerLanguage = true, it means the rule is valid for both C# and VB. // Thus, if there is a valid existing header containing both [*.cs] and [*.vb], then we prioritize it. // - If isPerLanguage = false, it means the rule is only valid for one of the languages. Thus, we // prioritize headers that contain only the file extension for the given language. // - If neither of the above hold true, we choose the last existing valid header. // - If no valid existing headers, we generate a new header. if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; } var textChange = new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry); return result.WithChanges(textChange); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; } var textChange = new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry); return result.WithChanges(textChange); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] if (_language is LanguageNames.CSharp or LanguageNames.VisualBasic) { // Insert a newline if not already present var lines = result.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } var compilerDiagOrNotPerLang = (_diagnostic != null && SuppressionHelpers.IsCompilerDiagnostic(_diagnostic)) || !_isPerLanguage; if (_language.Equals(LanguageNames.CSharp) && compilerDiagOrNotPerLang) { prefix += "[*.cs]\r\n"; } else if (_language.Equals(LanguageNames.VisualBasic) && compilerDiagOrNotPerLang) { prefix += "[*.vb]\r\n"; } else { prefix += "[*.{cs,vb}]\r\n"; } var textChange = new TextChange(new TextSpan(result.Length, 0), prefix + newEntry); return result.WithChanges(textChange); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration { /// <summary> /// Helper class to configure diagnostic severity or code style option value based on .editorconfig file /// </summary> internal sealed partial class ConfigurationUpdater { private enum ConfigurationKind { OptionValue, Severity, BulkConfigure } private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; private const string BulkConfigureAllAnalyzerDiagnosticsOptionKey = "dotnet_analyzer_diagnostic.severity"; private const string BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix = "dotnet_analyzer_diagnostic.category-"; private const string AllAnalyzerDiagnosticsCategory = ""; // Regular expression for .editorconfig header. // For example: "[*.cs] # Optional comment" // "[*.{vb,cs}]" // "[*] ; Optional comment" // "[ConsoleApp/Program.cs]" private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); // Regular expression for .editorconfig code style option entry. // For example: // 1. "dotnet_style_object_initializer = true # Optional comment" // 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment" // 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment" // 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment" // 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment" // // Regex groups: // 1. Option key // 2. Option value // 3. Optional severity suffix in option value, i.e. ':severity' suffix // 4. Optional comment suffix private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private readonly string? _optionNameOpt; private readonly string? _newOptionValueOpt; private readonly string _newSeverity; private readonly ConfigurationKind _configurationKind; private readonly Diagnostic? _diagnostic; private readonly string? _categoryToBulkConfigure; private readonly bool _isPerLanguage; private readonly Project _project; private readonly CancellationToken _cancellationToken; private readonly bool _addNewEntryIfNoExistingEntryFound; private readonly string _language; private ConfigurationUpdater( string? optionNameOpt, string? newOptionValueOpt, string newSeverity, ConfigurationKind configurationKind, Diagnostic? diagnosticToConfigure, string? categoryToBulkConfigure, bool isPerLanguage, Project project, bool addNewEntryIfNoExistingEntryFound, CancellationToken cancellationToken) { Debug.Assert(configurationKind != ConfigurationKind.OptionValue || !string.IsNullOrEmpty(newOptionValueOpt)); Debug.Assert(!string.IsNullOrEmpty(newSeverity)); Debug.Assert(diagnosticToConfigure != null ^ categoryToBulkConfigure != null); Debug.Assert((categoryToBulkConfigure != null) == (configurationKind == ConfigurationKind.BulkConfigure)); _optionNameOpt = optionNameOpt; _newOptionValueOpt = newOptionValueOpt; _newSeverity = newSeverity; _configurationKind = configurationKind; _diagnostic = diagnosticToConfigure; _categoryToBulkConfigure = categoryToBulkConfigure; _isPerLanguage = isPerLanguage; _project = project; _cancellationToken = cancellationToken; _addNewEntryIfNoExistingEntryFound = addNewEntryIfNoExistingEntryFound; _language = project.Language; } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the severity of the given <paramref name="diagnostic"/> is configured to be the given /// <paramref name="severity"/>. /// </summary> public static Task<Solution> ConfigureSeverityAsync( ReportDiagnostic severity, Diagnostic diagnostic, Project project, CancellationToken cancellationToken) { if (severity == ReportDiagnostic.Default) { severity = diagnostic.DefaultSeverity.ToReportDiagnostic(); } return ConfigureSeverityAsync(severity.ToEditorConfigString(), diagnostic, project, cancellationToken); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the severity of the given <paramref name="diagnostic"/> is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> ConfigureSeverityAsync( string editorConfigSeverity, Diagnostic diagnostic, Project project, CancellationToken cancellationToken) { // For option based code style diagnostic, try to find the .editorconfig key-value pair for the // option setting. var codeStyleOptionValues = GetCodeStyleOptionValuesForDiagnostic(diagnostic, project); ConfigurationUpdater updater; if (!codeStyleOptionValues.IsEmpty) { return ConfigureCodeStyleOptionsAsync( codeStyleOptionValues.Select(t => (t.optionName, t.currentOptionValue, t.isPerLanguage)), editorConfigSeverity, diagnostic, project, configurationKind: ConfigurationKind.Severity, cancellationToken); } else { updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.Severity, diagnostic, categoryToBulkConfigure: null, isPerLanguage: false, project, addNewEntryIfNoExistingEntryFound: true, cancellationToken); return updater.ConfigureAsync(); } } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the default severity of the diagnostics with the given <paramref name="category"/> is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> BulkConfigureSeverityAsync( string editorConfigSeverity, string category, Project project, CancellationToken cancellationToken) { Contract.ThrowIfFalse(!string.IsNullOrEmpty(category)); return BulkConfigureSeverityCoreAsync(editorConfigSeverity, category, project, cancellationToken); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the default severity of all diagnostics is configured to be the given /// <paramref name="editorConfigSeverity"/>. /// </summary> public static Task<Solution> BulkConfigureSeverityAsync( string editorConfigSeverity, Project project, CancellationToken cancellationToken) { return BulkConfigureSeverityCoreAsync(editorConfigSeverity, category: AllAnalyzerDiagnosticsCategory, project, cancellationToken); } private static Task<Solution> BulkConfigureSeverityCoreAsync( string editorConfigSeverity, string category, Project project, CancellationToken cancellationToken) { Contract.ThrowIfNull(category); var updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.BulkConfigure, diagnosticToConfigure: null, category, isPerLanguage: false, project, addNewEntryIfNoExistingEntryFound: true, cancellationToken); return updater.ConfigureAsync(); } /// <summary> /// Updates or adds an .editorconfig <see cref="AnalyzerConfigDocument"/> to the given <paramref name="project"/> /// so that the given <paramref name="optionName"/> is configured to have the given <paramref name="optionValue"/>. /// </summary> public static Task<Solution> ConfigureCodeStyleOptionAsync( string optionName, string optionValue, Diagnostic diagnostic, bool isPerLanguage, Project project, CancellationToken cancellationToken) => ConfigureCodeStyleOptionsAsync( SpecializedCollections.SingletonEnumerable((optionName, optionValue, isPerLanguage)), diagnostic.Severity.ToEditorConfigString(), diagnostic, project, configurationKind: ConfigurationKind.OptionValue, cancellationToken); private static async Task<Solution> ConfigureCodeStyleOptionsAsync( IEnumerable<(string optionName, string optionValue, bool isPerLanguage)> codeStyleOptionValues, string editorConfigSeverity, Diagnostic diagnostic, Project project, ConfigurationKind configurationKind, CancellationToken cancellationToken) { Debug.Assert(!codeStyleOptionValues.IsEmpty()); // For severity configuration for IDE code style diagnostics, we want to ensure the following: // 1. For code style option based entries, i.e. "%option_name% = %option_value%:%severity%, // we only update existing entries, but do not add a new entry. // 2. For "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity%" entries, we update existing entries, and if none found // we add a single new severity configuration entry for all code style options that share the same diagnostic ID. // This behavior is required to ensure that we always add the up-to-date dotnet_diagnostic based severity entry // so the IDE code style diagnostics can be enforced in build, as the compiler only understands dotnet_diagnostic entries. // See https://github.com/dotnet/roslyn/issues/44201 for more details. // First handle "%option_name% = %option_value%:%severity% entries. // For option value configuration, we always want to add new entry if no existing value is found. // For severity configuration, we only want to update existing value if found. var currentProject = project; var areAllOptionsPerLanguage = true; var addNewEntryIfNoExistingEntryFound = configurationKind != ConfigurationKind.Severity; foreach (var (optionName, optionValue, isPerLanguage) in codeStyleOptionValues) { Debug.Assert(!string.IsNullOrEmpty(optionName)); Debug.Assert(optionValue != null); var updater = new ConfigurationUpdater(optionName, optionValue, editorConfigSeverity, configurationKind, diagnostic, categoryToBulkConfigure: null, isPerLanguage, currentProject, addNewEntryIfNoExistingEntryFound, cancellationToken); var solution = await updater.ConfigureAsync().ConfigureAwait(false); currentProject = solution.GetProject(project.Id)!; areAllOptionsPerLanguage = areAllOptionsPerLanguage && isPerLanguage; } // For severity configuration, handle "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity%" entry. // We want to update existing entry + add new entry if no existing value is found. if (configurationKind == ConfigurationKind.Severity) { var updater = new ConfigurationUpdater(optionNameOpt: null, newOptionValueOpt: null, editorConfigSeverity, configurationKind: ConfigurationKind.Severity, diagnostic, categoryToBulkConfigure: null, isPerLanguage: areAllOptionsPerLanguage, currentProject, addNewEntryIfNoExistingEntryFound: true, cancellationToken); var solution = await updater.ConfigureAsync().ConfigureAwait(false); currentProject = solution.GetProject(project.Id)!; } return currentProject.Solution; } private async Task<Solution> ConfigureAsync() { // Find existing .editorconfig or generate a new one if none exists. var editorConfigDocument = FindOrGenerateEditorConfig(); if (editorConfigDocument == null) { return _project.Solution; } var solution = editorConfigDocument.Project.Solution; var originalText = await editorConfigDocument.GetTextAsync(_cancellationToken).ConfigureAwait(false); // Compute the updated text for analyzer config document. var newText = GetNewAnalyzerConfigDocumentText(originalText, editorConfigDocument); if (newText == null || newText.Equals(originalText)) { return solution; } // Add the newly added analyzer config document as a solution item. // The analyzer config document is not yet created, so we just mark the file // path for tracking and add it as a solution item whenever the file gets created by the code fix application. var service = _project.Solution.Workspace.Services.GetService<IAddSolutionItemService>(); service?.TrackFilePathAndAddSolutionItemWhenFileCreated(editorConfigDocument.FilePath); return solution.WithAnalyzerConfigDocumentText(editorConfigDocument.Id, newText); } private AnalyzerConfigDocument? FindOrGenerateEditorConfig() { var analyzerConfigPath = _diagnostic != null ? _project.TryGetAnalyzerConfigPathForDiagnosticConfiguration(_diagnostic) : _project.TryGetAnalyzerConfigPathForProjectConfiguration(); if (analyzerConfigPath == null) { return null; } if (_project.Solution?.FilePath == null) { // Project has no solution or solution without a file path. // Add analyzer config to just the current project. return _project.GetOrCreateAnalyzerConfigDocument(analyzerConfigPath); } // Otherwise, add analyzer config document to all applicable projects for the current project's solution. AnalyzerConfigDocument? analyzerConfigDocument = null; var analyzerConfigDirectory = PathUtilities.GetDirectoryName(analyzerConfigPath) ?? throw ExceptionUtilities.Unreachable; var currentSolution = _project.Solution; foreach (var projectId in _project.Solution.ProjectIds) { var project = currentSolution.GetProject(projectId); if (project?.FilePath?.StartsWith(analyzerConfigDirectory) == true) { var addedAnalyzerConfigDocument = project.GetOrCreateAnalyzerConfigDocument(analyzerConfigPath); if (addedAnalyzerConfigDocument != null) { analyzerConfigDocument ??= addedAnalyzerConfigDocument; currentSolution = addedAnalyzerConfigDocument.Project.Solution; } } } return analyzerConfigDocument; } private static ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)> GetCodeStyleOptionValuesForDiagnostic( Diagnostic diagnostic, Project project) { // For option based code style diagnostic, try to find the .editorconfig key-value pair for the // option setting. // For example, IDE diagnostics which are configurable with following code style option based .editorconfig entry: // "%option_name% = %option_value%:%severity% // we return '(option_name, new_option_value, new_severity)' var codeStyleOptions = GetCodeStyleOptionsForDiagnostic(diagnostic, project); if (!codeStyleOptions.IsEmpty) { var optionSet = project.Solution.Workspace.Options; var builder = ArrayBuilder<(string optionName, string currentOptionValue, bool isPerLanguage)>.GetInstance(); try { foreach (var (_, codeStyleOption, editorConfigLocation, isPerLanguage) in codeStyleOptions) { if (!TryGetEditorConfigStringParts(codeStyleOption, editorConfigLocation, optionSet, out var parts)) { // Did not find a match, bail out. return ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)>.Empty; } builder.Add((parts.optionName, parts.optionValue, isPerLanguage)); } return builder.ToImmutable(); } finally { builder.Free(); } } return ImmutableArray<(string optionName, string currentOptionValue, bool isPerLanguage)>.Empty; } internal static bool TryGetEditorConfigStringParts( ICodeStyleOption codeStyleOption, IEditorConfigStorageLocation2 editorConfigLocation, OptionSet optionSet, out (string optionName, string optionValue) parts) { var editorConfigString = editorConfigLocation.GetEditorConfigString(codeStyleOption, optionSet); if (!string.IsNullOrEmpty(editorConfigString)) { var match = s_optionEntryPattern.Match(editorConfigString); if (match.Success) { parts = (optionName: match.Groups[1].Value.Trim(), optionValue: match.Groups[2].Value.Trim()); return true; } } parts = default; return false; } internal static ImmutableArray<(OptionKey optionKey, ICodeStyleOption codeStyleOptionValue, IEditorConfigStorageLocation2 location, bool isPerLanguage)> GetCodeStyleOptionsForDiagnostic( Diagnostic diagnostic, Project project) { if (IDEDiagnosticIdToOptionMappingHelper.TryGetMappedOptions(diagnostic.Id, project.Language, out var options)) { var optionSet = project.Solution.Workspace.Options; using var _ = ArrayBuilder<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.GetInstance(out var builder); foreach (var option in options.OrderBy(option => option.Name)) { var editorConfigLocation = option.StorageLocations.OfType<IEditorConfigStorageLocation2>().FirstOrDefault(); if (editorConfigLocation != null) { var optionKey = new OptionKey(option, option.IsPerLanguage ? project.Language : null); if (optionSet.GetOption(optionKey) is ICodeStyleOption codeStyleOption) { builder.Add((optionKey, codeStyleOption, editorConfigLocation, option.IsPerLanguage)); continue; } } // Did not find a match. return ImmutableArray<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.Empty; } return builder.ToImmutable(); } return ImmutableArray<(OptionKey, ICodeStyleOption, IEditorConfigStorageLocation2, bool)>.Empty; } private SourceText? GetNewAnalyzerConfigDocumentText(SourceText originalText, AnalyzerConfigDocument editorConfigDocument) { // Check if an entry to configure the rule severity already exists in the .editorconfig file. // If it does, we update the existing entry with the new severity. var (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = CheckIfRuleExistsAndReplaceInFile(originalText, editorConfigDocument); if (newText != null) { return newText; } if (!_addNewEntryIfNoExistingEntryFound) { return originalText; } // We did not find any existing entry in the in the .editorconfig file to configure rule severity. // So we add a new configuration entry to the .editorconfig file. return AddMissingRule(originalText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } private (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) CheckIfRuleExistsAndReplaceInFile( SourceText result, AnalyzerConfigDocument editorConfigDocument) { // If there's an error finding the editorconfig directory, bail out. var editorConfigDirectory = PathUtilities.GetDirectoryName(editorConfigDocument.FilePath); if (editorConfigDirectory == null) { return (null, null, null); } var relativePath = string.Empty; var diagnosticFilePath = string.Empty; // If diagnostic SourceTree is null, it means either Location.None or Bulk configuration at root editorconfig, and thus no relative path. var diagnosticSourceTree = _diagnostic?.Location.SourceTree; if (diagnosticSourceTree != null) { // Finds the relative path between editorconfig directory and diagnostic filepath. diagnosticFilePath = diagnosticSourceTree.FilePath.ToLowerInvariant(); relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), diagnosticFilePath); relativePath = PathUtilities.NormalizeWithForwardSlash(relativePath); } TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in result.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; // Regex groups: // 1. Option key // 2. Option value // 3. Optional severity suffix, i.e. ':severity' suffix // 4. Optional comment suffix var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); // Verify the most recent header is a valid header if (mostRecentHeader != null && lastValidHeader != null && mostRecentHeader.Equals(lastValidHeader)) { // We found the rule in the file -- replace it with updated option value/severity. if (key.Equals(_optionNameOpt)) { // We found an option configuration entry of form: // "%option_name% = %option_value% // OR // "%option_name% = %option_value%:%severity% var newOptionValue = _configurationKind == ConfigurationKind.OptionValue ? $"{value.GetLeadingWhitespace()}{_newOptionValueOpt}{value.GetTrailingWhitespace()}" : value; var newSeverityValue = _configurationKind == ConfigurationKind.Severity && severitySuffixInValue.Length > 0 ? $":{_newSeverity}" : severitySuffixInValue; textChange = new TextChange(curLine.Span, $"{untrimmedKey}={newOptionValue}{newSeverityValue}{commentValue}"); } else { // We want to detect severity based entry only when we are configuring severity and have no option name specified. if (_configurationKind != ConfigurationKind.OptionValue && _optionNameOpt == null && severitySuffixInValue.Length == 0 && key.EndsWith(SeveritySuffix)) { // We found a rule configuration entry of severity based form: // "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity% // OR // "dotnet_analyzer_diagnostic.severity = %severity% // OR // "dotnet_analyzer_diagnostic.category-<%DiagnosticCategory%>.severity = %severity% var foundMatch = false; switch (_configurationKind) { case ConfigurationKind.Severity: RoslynDebug.Assert(_diagnostic != null); if (key.StartsWith(DiagnosticOptionPrefix, StringComparison.Ordinal)) { var diagIdLength = key.Length - (DiagnosticOptionPrefix.Length + SeveritySuffix.Length); if (diagIdLength > 0) { var diagId = key.Substring(DiagnosticOptionPrefix.Length, diagIdLength); foundMatch = string.Equals(diagId, _diagnostic.Id, StringComparison.OrdinalIgnoreCase); } } break; case ConfigurationKind.BulkConfigure: RoslynDebug.Assert(_categoryToBulkConfigure != null); if (_categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory) { foundMatch = key == BulkConfigureAllAnalyzerDiagnosticsOptionKey; } else { if (key.StartsWith(BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix, StringComparison.Ordinal)) { var categoryLength = key.Length - (BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix.Length + SeveritySuffix.Length); var category = key.Substring(BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix.Length, categoryLength); foundMatch = string.Equals(category, _categoryToBulkConfigure, StringComparison.OrdinalIgnoreCase); } } break; } if (foundMatch) { var newSeverityValue = $"{value.GetLeadingWhitespace()}{_newSeverity}{value.GetTrailingWhitespace()}"; textChange = new TextChange(curLine.Span, $"{untrimmedKey}={newSeverityValue}{commentValue}"); } } } } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { // We found a header entry such as '[*.cs]', '[*.vb]', etc. // Verify that header is valid. mostRecentHeader = curLine; var groups = s_headerPattern.Match(curLineText.Trim()).Groups; var mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); if (mostRecentHeaderText.Equals("*")) { lastValidHeader = mostRecentHeader; } else { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); // Creating the header regex string, ex. [*.{cs,vb}] => ((\.cs)|(\.vb)) var headerRegexStr = fileName + @"((\." + splicedFileExtensions[0] + ")"; for (var i = 1; i < splicedFileExtensions.Length; i++) { headerRegexStr += @"|(\." + splicedFileExtensions[i] + ")"; } headerRegexStr += ")"; var headerRegex = new Regex(headerRegexStr); // We check that the relative path of the .editorconfig file to the diagnostic file // matches the header regex pattern. if (headerRegex.IsMatch(relativePath)) { var match = headerRegex.Match(relativePath).Value; var matchWithoutExtension = match.Substring(0, match.LastIndexOf('.')); // Edge case: The below statement checks that we correctly handle cases such as a header of [m.cs] and // a file name of Program.cs. if (matchWithoutExtension.Contains(PathUtilities.GetFileName(diagnosticFilePath, false))) { // If the diagnostic's isPerLanguage = true, the rule is valid for both C# and VB. // For the purpose of adding missing rules later, we want to keep track of whether there is a // valid header that contains both [*.cs] and [*.vb]. // If isPerLanguage = false or a compiler diagnostic, the rule is only valid for one of the languages. // Thus, we want to keep track of whether there is an existing header that only contains [*.cs] or only // [*.vb], depending on the language. // We also keep track of the last valid header for the language. var isLanguageAgnosticEntry = (_diagnostic == null || !SuppressionHelpers.IsCompilerDiagnostic(_diagnostic)) && _isPerLanguage; if (isLanguageAgnosticEntry) { if ((_language.Equals(LanguageNames.CSharp) || _language.Equals(LanguageNames.VisualBasic)) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Contains("vb")) { lastValidSpecificHeader = mostRecentHeader; } } else if (splicedFileExtensions.Length == 1) { if (_language.Equals(LanguageNames.CSharp) && splicedFileExtensions.Contains("cs")) { lastValidSpecificHeader = mostRecentHeader; } else if (_language.Equals(LanguageNames.VisualBasic) && splicedFileExtensions.Contains("vb")) { lastValidSpecificHeader = mostRecentHeader; } } lastValidHeader = mostRecentHeader; } } // Location.None special case. else if (relativePath.IsEmpty() && new Regex(fileName).IsMatch(relativePath)) { if ((_language.Equals(LanguageNames.CSharp) && splicedFileExtensions.Contains("cs")) || (_language.Equals(LanguageNames.VisualBasic) && splicedFileExtensions.Contains("vb"))) { lastValidHeader = mostRecentHeader; } } } } // We want to keep track of how far this (valid) section spans. if (mostRecentHeader != null && lastValidHeader != null && mostRecentHeader.Equals(lastValidHeader)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (result.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } private SourceText? AddMissingRule( SourceText result, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) { // Create a new rule configuration entry for the given diagnostic ID or bulk configuration category. // If optionNameOpt and optionValueOpt are non-null, it indicates an option based diagnostic ID // which can be configured by a new entry such as: "%option_name% = %option_value%:%severity% // Otherwise, if diagnostic is non-null, it indicates a non-option diagnostic ID, // which can be configured by a new entry such as: "dotnet_diagnostic.<%DiagnosticId%>.severity = %severity% // Otherwise, it indicates a bulk configuration entry for default severity of a specific diagnostic category or all analyzer diagnostics, // which can be configured by a new entry such as: // 1. All analyzer diagnostics: "dotnet_analyzer_diagnostic.severity = %severity% // 2. Category configuration: "dotnet_analyzer_diagnostic.category-<%DiagnosticCategory%>.severity = %severity% var newEntry = !string.IsNullOrEmpty(_optionNameOpt) && !string.IsNullOrEmpty(_newOptionValueOpt) ? $"{_optionNameOpt} = {_newOptionValueOpt}" : _diagnostic != null ? $"{DiagnosticOptionPrefix}{_diagnostic.Id}{SeveritySuffix} = {_newSeverity}" : _categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory ? $"{BulkConfigureAllAnalyzerDiagnosticsOptionKey} = {_newSeverity}" : $"{BulkConfigureAnalyzerDiagnosticsByCategoryOptionPrefix}{_categoryToBulkConfigure}{SeveritySuffix} = {_newSeverity}"; // Insert a new line and comment text above the new entry var commentPrefix = _diagnostic != null ? $"{_diagnostic.Id}: {_diagnostic.Descriptor.Title}" : _categoryToBulkConfigure == AllAnalyzerDiagnosticsCategory ? "Default severity for all analyzer diagnostics" : $"Default severity for analyzer diagnostics with category '{_categoryToBulkConfigure}'"; newEntry = $"\r\n# {commentPrefix}\r\n{newEntry}\r\n"; // Check if have a correct existing header for the new entry. // - If the diagnostic's isPerLanguage = true, it means the rule is valid for both C# and VB. // Thus, if there is a valid existing header containing both [*.cs] and [*.vb], then we prioritize it. // - If isPerLanguage = false, it means the rule is only valid for one of the languages. Thus, we // prioritize headers that contain only the file extension for the given language. // - If neither of the above hold true, we choose the last existing valid header. // - If no valid existing headers, we generate a new header. if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; } var textChange = new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry); return result.WithChanges(textChange); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; } var textChange = new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry); return result.WithChanges(textChange); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] if (_language is LanguageNames.CSharp or LanguageNames.VisualBasic) { // Insert a newline if not already present var lines = result.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } var compilerDiagOrNotPerLang = (_diagnostic != null && SuppressionHelpers.IsCompilerDiagnostic(_diagnostic)) || !_isPerLanguage; if (_language.Equals(LanguageNames.CSharp) && compilerDiagOrNotPerLang) { prefix += "[*.cs]\r\n"; } else if (_language.Equals(LanguageNames.VisualBasic) && compilerDiagOrNotPerLang) { prefix += "[*.vb]\r\n"; } else { prefix += "[*.{cs,vb}]\r\n"; } var textChange = new TextChange(new TextSpan(result.Length, 0), prefix + newEntry); return result.WithChanges(textChange); } return null; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToCountConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./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.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 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; if ((destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { bool isExpressionTree = destination.IsNonGenericExpressionType(); if (isExpressionTree) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType, isExpressionTree); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { 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; } if (destination.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { 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, 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) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { 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.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 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; if ((destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { bool isExpressionTree = destination.IsNonGenericExpressionType(); if (isExpressionTree) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType, isExpressionTree); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { 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; } if (destination.SpecialType == SpecialType.System_Delegate && syntax.IsFeatureEnabled(MessageID.IDS_FeatureInferredDelegateType)) { // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { 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, 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) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { 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
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/VisualStudio/Core/Def/Storage/VisualStudioCloudCacheStorageServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared] internal class VisualStudioCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IAsyncServiceProvider _serviceProvider; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioCloudCacheStorageServiceFactory( IThreadingContext threadingContext, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _serviceProvider = (IAsyncServiceProvider)serviceProvider; } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) => new VisualStudioCloudCacheStorageService(_serviceProvider, _threadingContext, locationService); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared] internal class VisualStudioCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IAsyncServiceProvider _serviceProvider; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioCloudCacheStorageServiceFactory( IThreadingContext threadingContext, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _serviceProvider = (IAsyncServiceProvider)serviceProvider; } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) => new VisualStudioCloudCacheStorageService(_serviceProvider, _threadingContext, locationService); } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/Server/VBCSCompiler/DiagnosticListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/EditorFeatures/CSharpTest/SignatureHelp/AttributeSignatureHelpProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class AttributeSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(AttributeSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class SomethingAttribute : System.Attribute { } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary>Summary For Attribute</summary> public SomethingAttribute() { } } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; public SomethingAttribute(int i) => throw null; public SomethingAttribute(byte filtered) => throw null; } [[|Something(i: 1$$|])] class D { } "; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; public SomethingAttribute(int i) => throw null; public SomethingAttribute(byte filtered) => throw null; } [[|Something(i: null$$|])] class D { } "; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0), new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0, isSelected: true), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary> /// Summary For Attribute /// </summary> /// <param name=""someInteger"">Param someInteger</param> /// <param name=""someString"">Param someString</param> public SomethingAttribute(int someInteger, string someString) { } } [[|Something($$ |]class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } } [[|Something(22, $$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary> /// Summary For Attribute /// </summary> /// <param name=""someInteger"">Param someInteger</param> /// <param name=""someString"">Param someString</param> public SomethingAttribute(int someInteger, string someString) { } } [[|Something(22, $$ |]class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithClosingParen() { var markup = @" class SomethingAttribute : System.Attribute { } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan1() { await TestAsync( @"using System; class C { [[|Obsolete($$|])] void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan2() { await TestAsync( @"using System; class C { [[|Obsolete($$|])] void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan3() { await TestAsync( @"using System; class C { [[|Obsolete( $$|]] void Goo() { } }"); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(somethingElse: false, someParameter: $$22|])] class C { }"; await VerifyCurrentParameterNameAsync(markup, "someParameter"); } #endregion #region "Setting fields in attributes" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithValidField() { var markup = @" class SomethingAttribute : System.Attribute { public int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldReadonly() { var markup = @" class SomethingAttribute : System.Attribute { public readonly int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldStatic() { var markup = @" class SomethingAttribute : System.Attribute { public static int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldConst() { var markup = @" class SomethingAttribute : System.Attribute { public const int goo = 42; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Setting properties in attributes" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithValidProperty() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyStatic() { var markup = @" class SomethingAttribute : System.Attribute { public static int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyNoSetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get { return 0; } } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyNoGetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { set { } } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyPrivateGetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { private get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyPrivateSetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get; private set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(12544, "https://github.com/dotnet/roslyn/issues/12544")] [WorkItem(23664, "https://github.com/dotnet/roslyn/issues/23664")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOverriddenProperty() { var markup = @" cusing System; class BaseAttribute : Attribute { public virtual string Name { get; set; } } class DerivedAttribute : BaseAttribute { public override string Name { get; set; } } [[|Derived($$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"DerivedAttribute({CSharpFeaturesResources.Properties}: [Name = string])", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion #region "Setting fields and arguments" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters1() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "GooParameter", currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters2() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something(22, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters3() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something(22, null, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName1() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> public SomethingAttribute(int goo = 0) { } public int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, "GooParameter", currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName2() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> public SomethingAttribute(int goo = 0) { } public int goo { get; set; } } [[|Something(22, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 1)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something($$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(22,$$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(22, $$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableAlways() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableNever() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableAdvanced() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableMixed() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public MyAttribute(int x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public MyAttribute(int x, int y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret : System.Attribute { } #endif [Secret($$ void Goo() { } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret : System.Attribute { } #endif #if BAR [Secret($$ void Goo() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // [goo($$"; await TestAsync(markup); } [WorkItem(1081535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081535")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithBadParameterList() { var markup = @" class SomethingAttribute : System.Attribute { } [Something{$$] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class AttributeSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(AttributeSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class SomethingAttribute : System.Attribute { } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary>Summary For Attribute</summary> public SomethingAttribute() { } } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; public SomethingAttribute(int i) => throw null; public SomethingAttribute(byte filtered) => throw null; } [[|Something(i: 1$$|])] class D { } "; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(string i) => throw null; public SomethingAttribute(int i) => throw null; public SomethingAttribute(byte filtered) => throw null; } [[|Something(i: null$$|])] class D { } "; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("SomethingAttribute(int i)", currentParameterIndex: 0), new SignatureHelpTestItem("SomethingAttribute(string i)", currentParameterIndex: 0, isSelected: true), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } } [[|Something($$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary> /// Summary For Attribute /// </summary> /// <param name=""someInteger"">Param someInteger</param> /// <param name=""someString"">Param someString</param> public SomethingAttribute(int someInteger, string someString) { } } [[|Something($$ |]class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class SomethingAttribute : System.Attribute { public SomethingAttribute(int someInteger, string someString) { } } [[|Something(22, $$|]] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class SomethingAttribute : System.Attribute { /// <summary> /// Summary For Attribute /// </summary> /// <param name=""someInteger"">Param someInteger</param> /// <param name=""someString"">Param someString</param> public SomethingAttribute(int someInteger, string someString) { } } [[|Something(22, $$ |]class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithClosingParen() { var markup = @" class SomethingAttribute : System.Attribute { } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan1() { await TestAsync( @"using System; class C { [[|Obsolete($$|])] void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan2() { await TestAsync( @"using System; class C { [[|Obsolete($$|])] void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationSpan3() { await TestAsync( @"using System; class C { [[|Obsolete( $$|]] void Goo() { } }"); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(somethingElse: false, someParameter: $$22|])] class C { }"; await VerifyCurrentParameterNameAsync(markup, "someParameter"); } #endregion #region "Setting fields in attributes" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithValidField() { var markup = @" class SomethingAttribute : System.Attribute { public int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldReadonly() { var markup = @" class SomethingAttribute : System.Attribute { public readonly int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldStatic() { var markup = @" class SomethingAttribute : System.Attribute { public static int goo; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidFieldConst() { var markup = @" class SomethingAttribute : System.Attribute { public const int goo = 42; } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Setting properties in attributes" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithValidProperty() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyStatic() { var markup = @" class SomethingAttribute : System.Attribute { public static int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyNoSetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get { return 0; } } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyNoGetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { set { } } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyPrivateGetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { private get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithInvalidPropertyPrivateSetter() { var markup = @" class SomethingAttribute : System.Attribute { public int goo { get; private set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(12544, "https://github.com/dotnet/roslyn/issues/12544")] [WorkItem(23664, "https://github.com/dotnet/roslyn/issues/23664")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOverriddenProperty() { var markup = @" cusing System; class BaseAttribute : Attribute { public virtual string Name { get; set; } } class DerivedAttribute : BaseAttribute { public override string Name { get; set; } } [[|Derived($$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"DerivedAttribute({CSharpFeaturesResources.Properties}: [Name = string])", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion #region "Setting fields and arguments" [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters1() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "GooParameter", currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters2() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something(22, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithArgumentsAndNamedParameters3() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> /// <param name=""bar"">BarParameter</param> public SomethingAttribute(int goo = 0, string bar = null) { } public int fieldfoo { get; set; } public string fieldbar { get; set; } } [[|Something(22, null, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], [string bar = null], {CSharpFeaturesResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName1() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> public SomethingAttribute(int goo = 0) { } public int goo { get; set; } } [[|Something($$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, "GooParameter", currentParameterIndex: 0)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } [WorkItem(545425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545425")] [WorkItem(544139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544139")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestAttributeWithOptionalArgumentAndNamedParameterWithSameName2() { var markup = @" class SomethingAttribute : System.Attribute { /// <param name=""goo"">GooParameter</param> public SomethingAttribute(int goo = 0) { } public int goo { get; set; } } [[|Something(22, $$|])] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int goo = 0], {CSharpFeaturesResources.Properties}: [goo = int])", string.Empty, string.Empty, currentParameterIndex: 1)); // TODO: Bug 12319: Enable tests for script when this is fixed. await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something($$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(22,$$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" using System; class SomethingAttribute : Attribute { public SomethingAttribute(int someParameter, bool somethingElse) { } } [[|Something(22, $$|])] class C { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableAlways() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableNever() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableAdvanced() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public MyAttribute(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_Attribute_BrowsableMixed() { var markup = @" [MyAttribute($$ class Program { }"; var referencedCode = @" public class MyAttribute { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public MyAttribute(int x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public MyAttribute(int x, int y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret : System.Attribute { } #endif [Secret($$ void Goo() { } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret : System.Attribute { } #endif #if BAR [Secret($$ void Goo() { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // [goo($$"; await TestAsync(markup); } [WorkItem(1081535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081535")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithBadParameterList() { var markup = @" class SomethingAttribute : System.Attribute { } [Something{$$] class D { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/NoSourceGeneratedFilesPlaceholderItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed class NoSourceGeneratedFilesPlaceholderItem : BaseItem { public NoSourceGeneratedFilesPlaceholderItem() : base(SolutionExplorerShim.This_generator_is_not_generating_files) { } public override ImageMoniker IconMoniker => KnownMonikers.StatusInformationNoColor; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed class NoSourceGeneratedFilesPlaceholderItem : BaseItem { public NoSourceGeneratedFilesPlaceholderItem() : base(SolutionExplorerShim.This_generator_is_not_generating_files) { } public override ImageMoniker IconMoniker => KnownMonikers.StatusInformationNoColor; } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/CSharp/Portable/Parser/QuickScanner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class Lexer { // Maximum size of tokens/trivia that we cache and use in quick scanner. // From what I see in our own codebase, tokens longer then 40-50 chars are // not very common. // So it seems reasonable to limit the sizes to some round number like 42. internal const int MaxCachedTokenSize = 42; private enum QuickScanState : byte { Initial, FollowingWhite, FollowingCR, Ident, Number, Punctuation, Dot, CompoundPunctStart, DoneAfterNext, // we are relying on Bad state immediately following Done // to be able to detect exiting conditions in one "state >= Done" test. // And we are also relying on this to be the last item in the enum. Done, Bad = Done + 1 } private enum CharFlags : byte { White, // simple whitespace (space/tab) CR, // carriage return LF, // line feed Letter, // letter Digit, // digit 0-9 Punct, // some simple punctuation (parens, braces, comma, equals, question) Dot, // dot is different from other punctuation when followed by a digit (Ex: .9 ) CompoundPunctStart, // may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) Slash, // / Complex, // complex - causes scanning to abort EndOfFile, // legal type character (except !, which is contextually dictionary lookup } // PERF: Use byte instead of QuickScanState so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[,] s_stateTransitions = new byte[,] { // Initial { (byte)QuickScanState.Initial, // White (byte)QuickScanState.Initial, // CR (byte)QuickScanState.Initial, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Punctuation, // Punct (byte)QuickScanState.Dot, // Dot (byte)QuickScanState.CompoundPunctStart, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Bad, // EndOfFile }, // Following White { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Following CR { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Identifier { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Ident, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Number { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Bad, // Letter (might be 'e' or 'x' or suffix) (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (Number is followed by a dot - too complex for us to handle here). (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Dot { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (DotDot range token, exit so that we handle it in subsequent scanning code) (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Compound Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Bad, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Bad, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Done after next { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.Done, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, }; private SyntaxToken QuickScanSyntaxToken() { this.Start(); var state = QuickScanState.Initial; int i = TextWindow.Offset; int n = TextWindow.CharacterWindowCount; n = Math.Min(n, i + MaxCachedTokenSize); int hashCode = Hash.FnvOffsetBias; //localize frequently accessed fields var charWindow = TextWindow.CharacterWindow; var charPropLength = s_charProperties.Length; for (; i < n; i++) { char c = charWindow[i]; int uc = unchecked((int)c); var flags = uc < charPropLength ? (CharFlags)s_charProperties[uc] : CharFlags.Complex; state = (QuickScanState)s_stateTransitions[(int)state, (int)flags]; // NOTE: that Bad > Done and it is the only state like that // as a result, we will exit the loop on either Bad or Done. // the assert below will validate that these are the only states on which we exit // Also note that we must exit on Done or Bad // since the state machine does not have transitions for these states // and will promptly fail if we do not exit. if (state >= QuickScanState.Done) { goto exitWhile; } hashCode = unchecked((hashCode ^ uc) * Hash.FnvPrime); } state = QuickScanState.Bad; // ran out of characters in window exitWhile: TextWindow.AdvanceChar(i - TextWindow.Offset); Debug.Assert(state == QuickScanState.Bad || state == QuickScanState.Done, "can only exit with Bad or Done"); if (state == QuickScanState.Done) { // this is a good token! var token = _cache.LookupToken( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, i - TextWindow.LexemeRelativeStart, hashCode, _createQuickTokenFunction); return token; } else { TextWindow.Reset(TextWindow.LexemeStartPosition); return null; } } private readonly Func<SyntaxToken> _createQuickTokenFunction; private SyntaxToken CreateQuickToken() { #if DEBUG var quickWidth = TextWindow.Width; #endif TextWindow.Reset(TextWindow.LexemeStartPosition); var token = this.LexSyntaxToken(); #if DEBUG Debug.Assert(quickWidth == token.FullWidth); #endif return token; } // The following table classifies the first 0x180 Unicode characters. // # is marked complex as it may start directives. // PERF: Use byte instead of CharFlags so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[] s_charProperties = new[] { // 0 .. 31 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.White, // TAB (byte)CharFlags.LF, // LF (byte)CharFlags.White, // VT (byte)CharFlags.White, // FF (byte)CharFlags.CR, // CR (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 32 .. 63 (byte)CharFlags.White, // SPC (byte)CharFlags.CompoundPunctStart, // ! (byte)CharFlags.Complex, // " (byte)CharFlags.Complex, // # (byte)CharFlags.Complex, // $ (byte)CharFlags.CompoundPunctStart, // % (byte)CharFlags.CompoundPunctStart, // & (byte)CharFlags.Complex, // ' (byte)CharFlags.Punct, // ( (byte)CharFlags.Punct, // ) (byte)CharFlags.CompoundPunctStart, // * (byte)CharFlags.CompoundPunctStart, // + (byte)CharFlags.Punct, // , (byte)CharFlags.CompoundPunctStart, // - (byte)CharFlags.Dot, // . (byte)CharFlags.Slash, // / (byte)CharFlags.Digit, // 0 (byte)CharFlags.Digit, // 1 (byte)CharFlags.Digit, // 2 (byte)CharFlags.Digit, // 3 (byte)CharFlags.Digit, // 4 (byte)CharFlags.Digit, // 5 (byte)CharFlags.Digit, // 6 (byte)CharFlags.Digit, // 7 (byte)CharFlags.Digit, // 8 (byte)CharFlags.Digit, // 9 (byte)CharFlags.CompoundPunctStart, // : (byte)CharFlags.Punct, // ; (byte)CharFlags.CompoundPunctStart, // < (byte)CharFlags.CompoundPunctStart, // = (byte)CharFlags.CompoundPunctStart, // > (byte)CharFlags.CompoundPunctStart, // ? // 64 .. 95 (byte)CharFlags.Complex, // @ (byte)CharFlags.Letter, // A (byte)CharFlags.Letter, // B (byte)CharFlags.Letter, // C (byte)CharFlags.Letter, // D (byte)CharFlags.Letter, // E (byte)CharFlags.Letter, // F (byte)CharFlags.Letter, // G (byte)CharFlags.Letter, // H (byte)CharFlags.Letter, // I (byte)CharFlags.Letter, // J (byte)CharFlags.Letter, // K (byte)CharFlags.Letter, // L (byte)CharFlags.Letter, // M (byte)CharFlags.Letter, // N (byte)CharFlags.Letter, // O (byte)CharFlags.Letter, // P (byte)CharFlags.Letter, // Q (byte)CharFlags.Letter, // R (byte)CharFlags.Letter, // S (byte)CharFlags.Letter, // T (byte)CharFlags.Letter, // U (byte)CharFlags.Letter, // V (byte)CharFlags.Letter, // W (byte)CharFlags.Letter, // X (byte)CharFlags.Letter, // Y (byte)CharFlags.Letter, // Z (byte)CharFlags.Punct, // [ (byte)CharFlags.Complex, // \ (byte)CharFlags.Punct, // ] (byte)CharFlags.CompoundPunctStart, // ^ (byte)CharFlags.Letter, // _ // 96 .. 127 (byte)CharFlags.Complex, // ` (byte)CharFlags.Letter, // a (byte)CharFlags.Letter, // b (byte)CharFlags.Letter, // c (byte)CharFlags.Letter, // d (byte)CharFlags.Letter, // e (byte)CharFlags.Letter, // f (byte)CharFlags.Letter, // g (byte)CharFlags.Letter, // h (byte)CharFlags.Letter, // i (byte)CharFlags.Letter, // j (byte)CharFlags.Letter, // k (byte)CharFlags.Letter, // l (byte)CharFlags.Letter, // m (byte)CharFlags.Letter, // n (byte)CharFlags.Letter, // o (byte)CharFlags.Letter, // p (byte)CharFlags.Letter, // q (byte)CharFlags.Letter, // r (byte)CharFlags.Letter, // s (byte)CharFlags.Letter, // t (byte)CharFlags.Letter, // u (byte)CharFlags.Letter, // v (byte)CharFlags.Letter, // w (byte)CharFlags.Letter, // x (byte)CharFlags.Letter, // y (byte)CharFlags.Letter, // z (byte)CharFlags.Punct, // { (byte)CharFlags.CompoundPunctStart, // | (byte)CharFlags.Punct, // } (byte)CharFlags.CompoundPunctStart, // ~ (byte)CharFlags.Complex, // 128 .. 159 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 160 .. 191 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 192 .. (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class Lexer { // Maximum size of tokens/trivia that we cache and use in quick scanner. // From what I see in our own codebase, tokens longer then 40-50 chars are // not very common. // So it seems reasonable to limit the sizes to some round number like 42. internal const int MaxCachedTokenSize = 42; private enum QuickScanState : byte { Initial, FollowingWhite, FollowingCR, Ident, Number, Punctuation, Dot, CompoundPunctStart, DoneAfterNext, // we are relying on Bad state immediately following Done // to be able to detect exiting conditions in one "state >= Done" test. // And we are also relying on this to be the last item in the enum. Done, Bad = Done + 1 } private enum CharFlags : byte { White, // simple whitespace (space/tab) CR, // carriage return LF, // line feed Letter, // letter Digit, // digit 0-9 Punct, // some simple punctuation (parens, braces, comma, equals, question) Dot, // dot is different from other punctuation when followed by a digit (Ex: .9 ) CompoundPunctStart, // may be a part of compound punctuation. will be used only if followed by (not white) && (not punct) Slash, // / Complex, // complex - causes scanning to abort EndOfFile, // legal type character (except !, which is contextually dictionary lookup } // PERF: Use byte instead of QuickScanState so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[,] s_stateTransitions = new byte[,] { // Initial { (byte)QuickScanState.Initial, // White (byte)QuickScanState.Initial, // CR (byte)QuickScanState.Initial, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Punctuation, // Punct (byte)QuickScanState.Dot, // Dot (byte)QuickScanState.CompoundPunctStart, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Bad, // EndOfFile }, // Following White { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Following CR { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Identifier { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Ident, // Letter (byte)QuickScanState.Ident, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Number { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Bad, // Letter (might be 'e' or 'x' or suffix) (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (Number is followed by a dot - too complex for us to handle here). (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Dot { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Number, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Bad, // Dot (DotDot range token, exit so that we handle it in subsequent scanning code) (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Compound Punctuation { (byte)QuickScanState.FollowingWhite, // White (byte)QuickScanState.FollowingCR, // CR (byte)QuickScanState.DoneAfterNext, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Bad, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Bad, // Compound (byte)QuickScanState.Bad, // Slash (byte)QuickScanState.Bad, // Complex (byte)QuickScanState.Done, // EndOfFile }, // Done after next { (byte)QuickScanState.Done, // White (byte)QuickScanState.Done, // CR (byte)QuickScanState.Done, // LF (byte)QuickScanState.Done, // Letter (byte)QuickScanState.Done, // Digit (byte)QuickScanState.Done, // Punct (byte)QuickScanState.Done, // Dot (byte)QuickScanState.Done, // Compound (byte)QuickScanState.Done, // Slash (byte)QuickScanState.Done, // Complex (byte)QuickScanState.Done, // EndOfFile }, }; private SyntaxToken QuickScanSyntaxToken() { this.Start(); var state = QuickScanState.Initial; int i = TextWindow.Offset; int n = TextWindow.CharacterWindowCount; n = Math.Min(n, i + MaxCachedTokenSize); int hashCode = Hash.FnvOffsetBias; //localize frequently accessed fields var charWindow = TextWindow.CharacterWindow; var charPropLength = s_charProperties.Length; for (; i < n; i++) { char c = charWindow[i]; int uc = unchecked((int)c); var flags = uc < charPropLength ? (CharFlags)s_charProperties[uc] : CharFlags.Complex; state = (QuickScanState)s_stateTransitions[(int)state, (int)flags]; // NOTE: that Bad > Done and it is the only state like that // as a result, we will exit the loop on either Bad or Done. // the assert below will validate that these are the only states on which we exit // Also note that we must exit on Done or Bad // since the state machine does not have transitions for these states // and will promptly fail if we do not exit. if (state >= QuickScanState.Done) { goto exitWhile; } hashCode = unchecked((hashCode ^ uc) * Hash.FnvPrime); } state = QuickScanState.Bad; // ran out of characters in window exitWhile: TextWindow.AdvanceChar(i - TextWindow.Offset); Debug.Assert(state == QuickScanState.Bad || state == QuickScanState.Done, "can only exit with Bad or Done"); if (state == QuickScanState.Done) { // this is a good token! var token = _cache.LookupToken( TextWindow.CharacterWindow, TextWindow.LexemeRelativeStart, i - TextWindow.LexemeRelativeStart, hashCode, _createQuickTokenFunction); return token; } else { TextWindow.Reset(TextWindow.LexemeStartPosition); return null; } } private readonly Func<SyntaxToken> _createQuickTokenFunction; private SyntaxToken CreateQuickToken() { #if DEBUG var quickWidth = TextWindow.Width; #endif TextWindow.Reset(TextWindow.LexemeStartPosition); var token = this.LexSyntaxToken(); #if DEBUG Debug.Assert(quickWidth == token.FullWidth); #endif return token; } // The following table classifies the first 0x180 Unicode characters. // # is marked complex as it may start directives. // PERF: Use byte instead of CharFlags so the compiler can use array literal initialization. // The most natural type choice, Enum arrays, are not blittable due to a CLR limitation. private static readonly byte[] s_charProperties = new[] { // 0 .. 31 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.White, // TAB (byte)CharFlags.LF, // LF (byte)CharFlags.White, // VT (byte)CharFlags.White, // FF (byte)CharFlags.CR, // CR (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 32 .. 63 (byte)CharFlags.White, // SPC (byte)CharFlags.CompoundPunctStart, // ! (byte)CharFlags.Complex, // " (byte)CharFlags.Complex, // # (byte)CharFlags.Complex, // $ (byte)CharFlags.CompoundPunctStart, // % (byte)CharFlags.CompoundPunctStart, // & (byte)CharFlags.Complex, // ' (byte)CharFlags.Punct, // ( (byte)CharFlags.Punct, // ) (byte)CharFlags.CompoundPunctStart, // * (byte)CharFlags.CompoundPunctStart, // + (byte)CharFlags.Punct, // , (byte)CharFlags.CompoundPunctStart, // - (byte)CharFlags.Dot, // . (byte)CharFlags.Slash, // / (byte)CharFlags.Digit, // 0 (byte)CharFlags.Digit, // 1 (byte)CharFlags.Digit, // 2 (byte)CharFlags.Digit, // 3 (byte)CharFlags.Digit, // 4 (byte)CharFlags.Digit, // 5 (byte)CharFlags.Digit, // 6 (byte)CharFlags.Digit, // 7 (byte)CharFlags.Digit, // 8 (byte)CharFlags.Digit, // 9 (byte)CharFlags.CompoundPunctStart, // : (byte)CharFlags.Punct, // ; (byte)CharFlags.CompoundPunctStart, // < (byte)CharFlags.CompoundPunctStart, // = (byte)CharFlags.CompoundPunctStart, // > (byte)CharFlags.CompoundPunctStart, // ? // 64 .. 95 (byte)CharFlags.Complex, // @ (byte)CharFlags.Letter, // A (byte)CharFlags.Letter, // B (byte)CharFlags.Letter, // C (byte)CharFlags.Letter, // D (byte)CharFlags.Letter, // E (byte)CharFlags.Letter, // F (byte)CharFlags.Letter, // G (byte)CharFlags.Letter, // H (byte)CharFlags.Letter, // I (byte)CharFlags.Letter, // J (byte)CharFlags.Letter, // K (byte)CharFlags.Letter, // L (byte)CharFlags.Letter, // M (byte)CharFlags.Letter, // N (byte)CharFlags.Letter, // O (byte)CharFlags.Letter, // P (byte)CharFlags.Letter, // Q (byte)CharFlags.Letter, // R (byte)CharFlags.Letter, // S (byte)CharFlags.Letter, // T (byte)CharFlags.Letter, // U (byte)CharFlags.Letter, // V (byte)CharFlags.Letter, // W (byte)CharFlags.Letter, // X (byte)CharFlags.Letter, // Y (byte)CharFlags.Letter, // Z (byte)CharFlags.Punct, // [ (byte)CharFlags.Complex, // \ (byte)CharFlags.Punct, // ] (byte)CharFlags.CompoundPunctStart, // ^ (byte)CharFlags.Letter, // _ // 96 .. 127 (byte)CharFlags.Complex, // ` (byte)CharFlags.Letter, // a (byte)CharFlags.Letter, // b (byte)CharFlags.Letter, // c (byte)CharFlags.Letter, // d (byte)CharFlags.Letter, // e (byte)CharFlags.Letter, // f (byte)CharFlags.Letter, // g (byte)CharFlags.Letter, // h (byte)CharFlags.Letter, // i (byte)CharFlags.Letter, // j (byte)CharFlags.Letter, // k (byte)CharFlags.Letter, // l (byte)CharFlags.Letter, // m (byte)CharFlags.Letter, // n (byte)CharFlags.Letter, // o (byte)CharFlags.Letter, // p (byte)CharFlags.Letter, // q (byte)CharFlags.Letter, // r (byte)CharFlags.Letter, // s (byte)CharFlags.Letter, // t (byte)CharFlags.Letter, // u (byte)CharFlags.Letter, // v (byte)CharFlags.Letter, // w (byte)CharFlags.Letter, // x (byte)CharFlags.Letter, // y (byte)CharFlags.Letter, // z (byte)CharFlags.Punct, // { (byte)CharFlags.CompoundPunctStart, // | (byte)CharFlags.Punct, // } (byte)CharFlags.CompoundPunctStart, // ~ (byte)CharFlags.Complex, // 128 .. 159 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 160 .. 191 (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, (byte)CharFlags.Complex, // 192 .. (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Complex, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter, (byte)CharFlags.Letter }; } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/EditorFeatures/CSharpTest/Formatting/Indentation/SmartTokenFormatterFormatRangeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { [UseExportProvider] public class SmartTokenFormatterFormatRangeTests { [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task BeginningOfFile() { var code = @" using System;$$"; var expected = @" using System;"; Assert.NotNull(await Record.ExceptionAsync(() => AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.None))); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace1() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace2() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace3() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace4() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace5() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace6() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace7() { var code = @"using System; namespace NS { class Class { } namespace NS2 {} }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace8() { var code = @"using System; namespace NS { class Class { } namespace NS2 { } }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class1() { var code = @"using System; class Class { }$$"; var expected = @"using System; class Class { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class2() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class3() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class4() { var code = @"using System; class Class { delegate void Test(int i); }$$"; var expected = @"using System; class Class { delegate void Test(int i); }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class5() { var code = @"using System; class Class { delegate void Test(int i); void Method() { } }$$"; var expected = @"using System; class Class { delegate void Test(int i); void Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Interface1() { var code = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }$$"; var expected = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Struct1() { var code = @"using System; struct Struct { Struct(int i) { } }$$"; var expected = @"using System; struct Struct { Struct(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Enum1() { var code = @"using System; enum Enum { A = 1, B = 2, C = 3 }$$"; var expected = @"using System; enum Enum { A = 1, B = 2, C = 3 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList1() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList2() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList3() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList4() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList5() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList5b() { var code = @"using System; class Class { int Prop { get { return 1; }$$ } }"; var expected = @"using System; class Class { int Prop { get { return 1; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList6() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList7() { var code = @"using System; class Class { int Prop { get { return 1;$$ } }"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList8() { var code = @"class C { int Prop { get { return 0; }$$ } }"; var expected = @"class C { int Prop { get { return 0; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfTheory] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [InlineData("get")] [InlineData("set")] [InlineData("init")] public async Task AccessorList9(string accessor) { var code = $@"class C {{ int Prop {{ {accessor} {{ ; }}$$ }} }}"; var expected = $@"class C {{ int Prop {{ {accessor} {{ ; }} }} }}"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList10() { var code = @"class C { event EventHandler E { add { }$$ remove { } } }"; var expected = @"class C { event EventHandler E { add { } remove { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList11() { var code = @"class C { event EventHandler E { add { } remove { }$$ } }"; var expected = @"class C { event EventHandler E { add { } remove { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block1() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block2() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block3() { var code = @"using System; class Class { public int Method() { }$$ }"; var expected = @"using System; class Class { public int Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block4() { var code = @"using System; class Class { public static Class operator +(Class c1, Class c2) { }$$ }"; var expected = @"using System; class Class { public static Class operator +(Class c1, Class c2) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block5() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block6() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block7() { var code = @"using System; class Class { void Method() { { { }$$"; var expected = @"using System; class Class { void Method() { { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block8() { var code = @"using System; class Class { void Method() { { { }$$ }"; var expected = @"using System; class Class { void Method() { { { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement1() { var code = @"using System; class Class { void Method() { switch (a) { case 1: break; }$$ } }"; var expected = @"using System; class Class { void Method() { switch (a) { case 1: break; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement2() { var code = @"using System; class Class { void Method() { switch (true) { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement3() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement4() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer1() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer2() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer3() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer4() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer5() { var code = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer6() { var code = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement2() { var code = @"using System; class Class { void Method() { if (true) { }$$ }"; var expected = @"using System; class Class { void Method() { if (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement3() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement4() { var code = @"using System; class Class { void Method() { while (true) { }$$ }"; var expected = @"using System; class Class { void Method() { while (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(8413, "https://github.com/dotnet/roslyn/issues/8413")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatementDoBlockAlone() { var code = @"using System; class Class { void Method() { do { }$$ } }"; var expected = @"using System; class Class { void Method() { do { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement5() { var code = @"using System; class Class { void Method() { do { } while(true);$$ } }"; var expected = @"using System; class Class { void Method() { do { } while (true); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement6() { var code = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { }$$ }"; var expected = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement7() { var code = @"using System; class Class { void Method() { foreach (var i in collection) { }$$ }"; var expected = @"using System; class Class { void Method() { foreach (var i in collection) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement8() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) { }$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement9() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$"; var expected = @"using System; class Class { void Method() { if (true) int i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FieldlInitializer() { var code = @"using System; class Class { string str = Console.Title;$$ "; var expected = @"using System; class Class { string str = Console.Title; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayFieldlInitializer() { var code = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" };$$ "; var expected = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" }; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ExpressionValuedPropertyInitializer() { var code = @"using System; class Class { public int Three => 1+2;$$ "; var expected = @"using System; class Class { public int Three => 1 + 2; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement10() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$ }"; var expected = @"using System; class Class { void Method() { if (true) int i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement11() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement12() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement13() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do(); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement14() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement15() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement16() { var code = @"using System; class Class { void Method() { do i = 10;$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement17() { var code = @"using System; class Class { void Method() { do i = 10; while (true);$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; while (true); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement1() { var code = @"using System; class Class { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement2() { var code = @"using System; class Class { void Method(int i) { } void Method2() { }$$ }"; var expected = @"using System; class Class { void Method(int i) { } void Method2() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement3() { var code = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 };$$ }"; var expected = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 }; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement4() { var code = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement5() { var code = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement6() { var code = @" using System; using System.Linq;$$"; var expected = @" using System; using System.Linq;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement7() { var code = @" using System; namespace NS { } namespace NS2 { }$$"; var expected = @" using System; namespace NS { } namespace NS2 { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement8() { var code = @"using System; namespace NS { class Class { } class Class1 { }$$ }"; var expected = @"using System; namespace NS { class Class { } class Class1 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement2() { var code = @"using System; class Class { void Method() { if (true) { } else { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement3() { var code = @"using System; class Class { void Method() { if (true) { } else if (false) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else if (false) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement4() { var code = @"using System; class Class { void Method() { if (true) return ; else if (false) return ;$$"; var expected = @"using System; class Class { void Method() { if (true) return; else if (false) return;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement1() { var code = @"using System; class Class { void Method() { try { }$$"; var expected = @"using System; class Class { void Method() { try { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement2() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement3() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { } catch (Exception ex2) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { } catch (Exception ex2) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement4() { var code = @"using System; class Class { void Method() { try { } finally { }$$"; var expected = @"using System; class Class { void Method() { try { } finally { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(6645, "https://github.com/dotnet/roslyn/issues/6645")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement5() { var code = @"using System; class Class { void Method() { try { }$$ } }"; var expected = @"using System; class Class { void Method() { try { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(537555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")] public async Task SingleLine() { var code = @"class C { void M() { C.M( );$$ } }"; var expected = @"class C { void M() { C.M(); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task StringLiterals() { var code = @"class C { void M() { C.M(""Test {0}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.StringLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CharLiterals() { var code = @"class C { void M() { C.M('}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task CharLiterals1() { var code = @"';$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Comments() { var code = @"class C { void M() { // { }$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FirstLineInFile() { var code = @"using System;$$"; await AutoFormatOnSemicolonAsync(code, "using System;", SyntaxKind.UsingKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label1() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label2() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label3() { var code = @"class C { void Method() { int base = 10; L : int i = 20;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label4() { var code = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label6() { var code = @"class C { void Method() { L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537776, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537776")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens() { var code = @"class Class1 { int goo() return 0; }$$ }"; var expected = @"class Class1 { int goo() return 0; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.ClassKeyword); } [WorkItem(537779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537779")] [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens2() { var code = @"class Class1 { void Goo() { Object o=new Object);$$ } }"; var expected = @"class Class1 { void Goo() { Object o=new Object); } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WorkItem(537793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537793")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Delegate1() { var code = @"delegate void MyDelegate(int a,int b);$$"; var expected = @"delegate void MyDelegate(int a, int b);"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.DelegateKeyword); } [WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DoubleInitializer() { var code = @"class C { void Method() { int[,] a ={{ 1 , 1 }$$ } }"; var expected = @"class C { void Method() { int[,] a ={{ 1 , 1 } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingToken1() { var code = @"public class Class1 { int a = 1}$$; }"; var expected = @"public class Class1 { int a = 1}; }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.PublicKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer1() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 }$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer2() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 } ;$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 }; }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MalformedCode() { var code = @"namespace ClassLibrary1 { public class Class1 { int a}$$; } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { int a}; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.ColonToken); } [Fact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label :$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.None); } [WpfFact] [WorkItem(538793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538793")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : Console.WriteLine(10) ;$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label: Console.WriteLine(10); } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(3186, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a=2;$$ else a = 3; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a = 2; else a = 3; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(538391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538391")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement2() { var code = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8;$$ else a = 10; } }"; var expected = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8; else a = 10; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(8385, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NullCoalescingOperator() { var code = @"class C { void M() { object o2 = null??null;$$ } }"; var expected = @"class C { void M() { object o2 = null ?? null; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(541517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541517")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchDefault() { var code = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default:$$ } } }"; var expected = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default: } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens1() { var code = @"class Program { static void Main(string[] args) { gl::$$ } }"; var expected = @"class Program { static void Main(string[] args) { gl:: } }"; await AutoFormatOnMarkerAsync( code, expected, SyntaxKind.ColonColonToken, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens2() { var code = @"class C { void M() { M(() => { }$$ } }"; var expected = @"class C { void M() { M(() => { } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.EqualsGreaterThanToken); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task UsingAlias() { var code = @"using Alias=System;$$"; var expected = @"using Alias = System;"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.UsingKeyword); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NoLineChangeWithSyntaxError() { var code = @"struct Goo { public int member; } class Program{ void Main() { var f = new Goo { member;$$ } } }"; var expected = @"struct Goo { public int member; } class Program{ void Main() { var f = new Goo { member; } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfTheory] [CombinatorialData] [WorkItem(620568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620568")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void SkippedTokens1(bool useTabs) { var code = @";$$*"; var expected = @";*"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor(bool useTabs) { var code = @"class C { int Prop { get ;$$ }"; var expected = @"class C { int Prop { get; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor2(bool useTabs) { var code = @"class C { int Prop { get; set ;$$ }"; var expected = @"class C { int Prop { get; set; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor3(bool useTabs) { var code = @"class C { int Prop { get; set ; }$$ }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(784674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784674")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor4(bool useTabs) { var code = @"class C { int Prop { get;$$ } }"; var expected = @"class C { int Prop { get; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor5(bool useTabs) { var code = @"class C { int Prop { get; set ;$$ } }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor6(bool useTabs) { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor7(bool useTabs) { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NestedUsingStatement(bool useTabs) { var code = @"class C { public void M() { using (null) using(null)$$ } }"; var expected = @"class C { public void M() { using (null) using (null) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NestedNotUsingStatement(bool useTabs) { var code = @"class C { public void M() { using (null) for(;;)$$ } }"; var expected = @"class C { public void M() { using (null) for(;;) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { using (null) fixed (void* ptr = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedCheckedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) checked { }$$ } }"; var expected = @"class C { public void M() { using (null) checked { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedUncheckedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) unchecked { }$$ } }"; var expected = @"class C { public void M() { using (null) unchecked { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedUsingStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr = &i) using (null)$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) using (null) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedNotFixedStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr = &i) if (false) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) if (false) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NotFixedStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { if (false) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { if (false) fixed (void* ptr = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstStatementOfBlock(bool useTabs) { var code = @"class C { public void M() {int s;$$ } }"; var expected = @"class C { public void M() { int s; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMemberofType(bool useTabs) { var code = @"class C {int s;$$ public void M() { } }"; var expected = @"class C { int s; public void M() { } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMethodMemberofType(bool useTabs) { var code = @"interface C {void s();$$ }"; var expected = @"interface C { void s(); }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForConstructor(bool useTabs) { var code = @"class C {public C()=>f=1;$$ }"; var expected = @"class C { public C() => f = 1; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForDestructor(bool useTabs) { var code = @"class C {~C()=>f=1;$$ }"; var expected = @"class C { ~C() => f = 1; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForOperator(bool useTabs) { var code = @"class C {public static C operator +(C left, C right)=>field=1;$$ static int field; }"; var expected = @"class C { public static C operator +(C left, C right) => field = 1; static int field; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMemberOfNamespace(bool useTabs) { var code = @"namespace C {delegate void s();$$ }"; var expected = @"namespace C { delegate void s(); }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZero(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #if #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if # } } "; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZeroWithCode(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #if int s = 10; #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if int s = 10; # } } "; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZeroWithBrokenElseDirective(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #else #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #else # } } "; AutoFormatToken(code, expected, useTabs); } internal static void AutoFormatToken(string markup, string expected, bool useTabs) { if (useTabs) { markup = markup.Replace(" ", "\t"); expected = expected.Replace(" ", "\t"); } using var workspace = TestWorkspace.CreateCSharp(markup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var subjectDocument = workspace.Documents.Single(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create()); var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } private static Tuple<OptionSet, IEnumerable<AbstractFormattingRule>> GetService( TestWorkspace workspace) { var options = workspace.Options; return Tuple.Create(options, Formatter.GetDefaultFormattingRules(workspace, LanguageNames.CSharp)); } private static Task AutoFormatOnColonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.ColonToken, startTokenKind); private static Task AutoFormatOnSemicolonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.SemicolonToken, startTokenKind); private static Task AutoFormatOnCloseBraceAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.CloseBraceToken, startTokenKind); private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, SyntaxKind tokenKind, SyntaxKind startTokenKind) { await AutoFormatOnMarkerAsync(initialMarkup, expected, useTabs: false, tokenKind, startTokenKind).ConfigureAwait(false); await AutoFormatOnMarkerAsync(initialMarkup.Replace(" ", "\t"), expected.Replace(" ", "\t"), useTabs: true, tokenKind, startTokenKind).ConfigureAwait(false); } private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, bool useTabs, SyntaxKind tokenKind, SyntaxKind startTokenKind) { using var workspace = TestWorkspace.CreateCSharp(initialMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var tuple = GetService(workspace); var testDocument = workspace.Documents.Single(); var buffer = testDocument.GetTextBuffer(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(); var endToken = root.FindToken(position); if (position == endToken.SpanStart && !endToken.GetPreviousToken().IsKind(SyntaxKind.None)) { endToken = endToken.GetPreviousToken(); } Assert.Equal(tokenKind, endToken.Kind()); var formatter = new CSharpSmartTokenFormatter(tuple.Item1, tuple.Item2, root); var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken); if (tokenRange == null) { Assert.Equal(SyntaxKind.None, startTokenKind); return; } Assert.Equal(startTokenKind, tokenRange.Value.Item1.Kind()); if (tokenRange.Value.Item1.Equals(tokenRange.Value.Item2)) { return; } var changes = formatter.FormatRange(workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, CancellationToken.None); var actual = GetFormattedText(buffer, changes); Assert.Equal(expected, actual); } private static string GetFormattedText(ITextBuffer buffer, IList<TextChange> changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } return buffer.CurrentSnapshot.GetText(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { [UseExportProvider] public class SmartTokenFormatterFormatRangeTests { [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task BeginningOfFile() { var code = @" using System;$$"; var expected = @" using System;"; Assert.NotNull(await Record.ExceptionAsync(() => AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.None))); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace1() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace2() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace3() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace4() { var code = @"using System; namespace NS { }$$"; var expected = @"using System; namespace NS { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace5() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace6() { var code = @"using System; namespace NS { class Class { } }$$"; var expected = @"using System; namespace NS { class Class { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace7() { var code = @"using System; namespace NS { class Class { } namespace NS2 {} }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Namespace8() { var code = @"using System; namespace NS { class Class { } namespace NS2 { } }$$"; var expected = @"using System; namespace NS { class Class { } namespace NS2 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class1() { var code = @"using System; class Class { }$$"; var expected = @"using System; class Class { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class2() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class3() { var code = @"using System; class Class { void Method(int i) { } }$$"; var expected = @"using System; class Class { void Method(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class4() { var code = @"using System; class Class { delegate void Test(int i); }$$"; var expected = @"using System; class Class { delegate void Test(int i); }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Class5() { var code = @"using System; class Class { delegate void Test(int i); void Method() { } }$$"; var expected = @"using System; class Class { delegate void Test(int i); void Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Interface1() { var code = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }$$"; var expected = @"using System; interface II { delegate void Test(int i); int Prop { get; set; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Struct1() { var code = @"using System; struct Struct { Struct(int i) { } }$$"; var expected = @"using System; struct Struct { Struct(int i) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Enum1() { var code = @"using System; enum Enum { A = 1, B = 2, C = 3 }$$"; var expected = @"using System; enum Enum { A = 1, B = 2, C = 3 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList1() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList2() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList3() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList4() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.GetKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList5() { var code = @"using System; class Class { int Prop { get { return 1; }$$"; var expected = @"using System; class Class { int Prop { get { return 1; }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList5b() { var code = @"using System; class Class { int Prop { get { return 1; }$$ } }"; var expected = @"using System; class Class { int Prop { get { return 1; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList6() { var code = @"using System; class Class { int Prop { get { return 1; } }$$"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.IntKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList7() { var code = @"using System; class Class { int Prop { get { return 1;$$ } }"; var expected = @"using System; class Class { int Prop { get { return 1; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList8() { var code = @"class C { int Prop { get { return 0; }$$ } }"; var expected = @"class C { int Prop { get { return 0; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfTheory] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [InlineData("get")] [InlineData("set")] [InlineData("init")] public async Task AccessorList9(string accessor) { var code = $@"class C {{ int Prop {{ {accessor} {{ ; }}$$ }} }}"; var expected = $@"class C {{ int Prop {{ {accessor} {{ ; }} }} }}"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList10() { var code = @"class C { event EventHandler E { add { }$$ remove { } } }"; var expected = @"class C { event EventHandler E { add { } remove { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(16984, "https://github.com/dotnet/roslyn/issues/16984")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task AccessorList11() { var code = @"class C { event EventHandler E { add { } remove { }$$ } }"; var expected = @"class C { event EventHandler E { add { } remove { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block1() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block2() { var code = @"using System; class Class { public int Method() { }$$"; var expected = @"using System; class Class { public int Method() { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block3() { var code = @"using System; class Class { public int Method() { }$$ }"; var expected = @"using System; class Class { public int Method() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block4() { var code = @"using System; class Class { public static Class operator +(Class c1, Class c2) { }$$ }"; var expected = @"using System; class Class { public static Class operator +(Class c1, Class c2) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block5() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block6() { var code = @"using System; class Class { void Method() { { }$$"; var expected = @"using System; class Class { void Method() { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block7() { var code = @"using System; class Class { void Method() { { { }$$"; var expected = @"using System; class Class { void Method() { { { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Block8() { var code = @"using System; class Class { void Method() { { { }$$ }"; var expected = @"using System; class Class { void Method() { { { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement1() { var code = @"using System; class Class { void Method() { switch (a) { case 1: break; }$$ } }"; var expected = @"using System; class Class { void Method() { switch (a) { case 1: break; } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement2() { var code = @"using System; class Class { void Method() { switch (true) { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement3() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchStatement4() { var code = @"using System; class Class { void Method() { switch (true) { case 1: { }$$"; var expected = @"using System; class Class { void Method() { switch (true) { case 1: { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.ColonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer1() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer2() { var code = @"using System; class Class { void Method() { var arr = new int[] { }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer3() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer4() { var code = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }$$"; var expected = @"using System; class Class { void Method() { var arr = new { A = 1, B = 2 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer5() { var code = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Initializer6() { var code = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }$$"; var expected = @"using System; class Class { void Method() { var arr = new int[] { 1, 2, 3, 4, 5 }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement2() { var code = @"using System; class Class { void Method() { if (true) { }$$ }"; var expected = @"using System; class Class { void Method() { if (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement3() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement4() { var code = @"using System; class Class { void Method() { while (true) { }$$ }"; var expected = @"using System; class Class { void Method() { while (true) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(8413, "https://github.com/dotnet/roslyn/issues/8413")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatementDoBlockAlone() { var code = @"using System; class Class { void Method() { do { }$$ } }"; var expected = @"using System; class Class { void Method() { do { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement5() { var code = @"using System; class Class { void Method() { do { } while(true);$$ } }"; var expected = @"using System; class Class { void Method() { do { } while (true); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement6() { var code = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { }$$ }"; var expected = @"using System; class Class { void Method() { for (int i = 0; i < 10; i++) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement7() { var code = @"using System; class Class { void Method() { foreach (var i in collection) { }$$ }"; var expected = @"using System; class Class { void Method() { foreach (var i in collection) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement8() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) { }$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement9() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$"; var expected = @"using System; class Class { void Method() { if (true) int i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FieldlInitializer() { var code = @"using System; class Class { string str = Console.Title;$$ "; var expected = @"using System; class Class { string str = Console.Title; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayFieldlInitializer() { var code = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" };$$ "; var expected = @"using System; namespace NS { class Class { string[] strArr = { ""1"", ""2"" }; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ExpressionValuedPropertyInitializer() { var code = @"using System; class Class { public int Three => 1+2;$$ "; var expected = @"using System; class Class { public int Three => 1 + 2; "; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement10() { var code = @"using System; class Class { void Method() { if (true) int i = 10;$$ }"; var expected = @"using System; class Class { void Method() { if (true) int i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement11() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement12() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement13() { var code = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do();$$ }"; var expected = @"using System; class Class { void Method() { using (var resource = GetResource()) resource.Do(); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement14() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement15() { var code = @"using System; class Class { void Method() { do i = 10;$$"; var expected = @"using System; class Class { void Method() { do i = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement16() { var code = @"using System; class Class { void Method() { do i = 10;$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task EmbeddedStatement17() { var code = @"using System; class Class { void Method() { do i = 10; while (true);$$ }"; var expected = @"using System; class Class { void Method() { do i = 10; while (true); }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement1() { var code = @"using System; class Class { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement2() { var code = @"using System; class Class { void Method(int i) { } void Method2() { }$$ }"; var expected = @"using System; class Class { void Method(int i) { } void Method2() { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement3() { var code = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 };$$ }"; var expected = @"using System; class Class { void Method(int i) { } A a = new A { Prop = 1, Prop2 = 2 }; }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement4() { var code = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; int i2 = 10;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement5() { var code = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;$$"; var expected = @"using System; class Class { void Method(int i) { int i = 10; if (true) i = 50;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement6() { var code = @" using System; using System.Linq;$$"; var expected = @" using System; using System.Linq;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement7() { var code = @" using System; namespace NS { } namespace NS2 { }$$"; var expected = @" using System; namespace NS { } namespace NS2 { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FollowPreviousElement8() { var code = @"using System; namespace NS { class Class { } class Class1 { }$$ }"; var expected = @"using System; namespace NS { class Class { } class Class1 { } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.CloseBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement1() { var code = @"using System; class Class { void Method() { if (true) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement2() { var code = @"using System; class Class { void Method() { if (true) { } else { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement3() { var code = @"using System; class Class { void Method() { if (true) { } else if (false) { }$$"; var expected = @"using System; class Class { void Method() { if (true) { } else if (false) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task IfStatement4() { var code = @"using System; class Class { void Method() { if (true) return ; else if (false) return ;$$"; var expected = @"using System; class Class { void Method() { if (true) return; else if (false) return;"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement1() { var code = @"using System; class Class { void Method() { try { }$$"; var expected = @"using System; class Class { void Method() { try { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement2() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement3() { var code = @"using System; class Class { void Method() { try { } catch ( Exception ex) { } catch (Exception ex2) { }$$"; var expected = @"using System; class Class { void Method() { try { } catch (Exception ex) { } catch (Exception ex2) { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement4() { var code = @"using System; class Class { void Method() { try { } finally { }$$"; var expected = @"using System; class Class { void Method() { try { } finally { }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(6645, "https://github.com/dotnet/roslyn/issues/6645")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task TryStatement5() { var code = @"using System; class Class { void Method() { try { }$$ } }"; var expected = @"using System; class Class { void Method() { try { } } }"; await AutoFormatOnCloseBraceAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(537555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537555")] public async Task SingleLine() { var code = @"class C { void M() { C.M( );$$ } }"; var expected = @"class C { void M() { C.M(); } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task StringLiterals() { var code = @"class C { void M() { C.M(""Test {0}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.StringLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task CharLiterals() { var code = @"class C { void M() { C.M('}$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task CharLiterals1() { var code = @"';$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.CharacterLiteralToken, SyntaxKind.None); } [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Comments() { var code = @"class C { void M() { // { }$$"; var expected = string.Empty; await AutoFormatOnMarkerAsync(code, expected, SyntaxKind.OpenBraceToken, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task FirstLineInFile() { var code = @"using System;$$"; await AutoFormatOnSemicolonAsync(code, "using System;", SyntaxKind.UsingKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label1() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label2() { var code = @"class C { void Method() { L : int i = 20;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label3() { var code = @"class C { void Method() { int base = 10; L : int i = 20;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label4() { var code = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { int base = 10; L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Label6() { var code = @"class C { void Method() { L: int i = 20; int nextLine = 30 ;$$ } }"; var expected = @"class C { void Method() { L: int i = 20; int nextLine = 30; } }"; await AutoFormatOnSemicolonAsync(code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537776, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537776")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens() { var code = @"class Class1 { int goo() return 0; }$$ }"; var expected = @"class Class1 { int goo() return 0; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.ClassKeyword); } [WorkItem(537779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537779")] [Fact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DisappearedTokens2() { var code = @"class Class1 { void Goo() { Object o=new Object);$$ } }"; var expected = @"class Class1 { void Goo() { Object o=new Object); } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WorkItem(537793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537793")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Delegate1() { var code = @"delegate void MyDelegate(int a,int b);$$"; var expected = @"delegate void MyDelegate(int a, int b);"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.DelegateKeyword); } [WorkItem(537827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537827")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task DoubleInitializer() { var code = @"class C { void Method() { int[,] a ={{ 1 , 1 }$$ } }"; var expected = @"class C { void Method() { int[,] a ={{ 1 , 1 } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingToken1() { var code = @"public class Class1 { int a = 1}$$; }"; var expected = @"public class Class1 { int a = 1}; }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.PublicKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer1() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 }$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.NewKeyword); } [WpfFact] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task ArrayInitializer2() { var code = @"public class Class1 { var a = new [] { 1, 2, 3, 4 } ;$$ }"; var expected = @"public class Class1 { var a = new[] { 1, 2, 3, 4 }; }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537825")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MalformedCode() { var code = @"namespace ClassLibrary1 { public class Class1 { int a}$$; } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { int a}; } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(584599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/584599")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_SwitchLabel_Comment2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1 :$$ } } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { switch(E.Type) { case 2: // test case 1: } } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.ColonToken); } [Fact] [WorkItem(537804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537804")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label :$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.None); } [WpfFact] [WorkItem(538793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538793")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task Colon_Label2() { var code = @"namespace ClassLibrary1 { public class Class1 { void Test() { label : Console.WriteLine(10) ;$$ } } }"; var expected = @"namespace ClassLibrary1 { public class Class1 { void Test() { label: Console.WriteLine(10); } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(3186, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a=2;$$ else a = 3; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int a = 0; if (a == 0) a = 1; else if (a == 1) a = 2; else a = 3; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(538391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538391")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SemicolonInElseIfStatement2() { var code = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8;$$ else a = 10; } }"; var expected = @"public class Class1 { void Method() { int a = 1; if (a == 0) a = 8; else a = 10; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(8385, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NullCoalescingOperator() { var code = @"class C { void M() { object o2 = null??null;$$ } }"; var expected = @"class C { void M() { object o2 = null ?? null; } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(541517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541517")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task SwitchDefault() { var code = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default:$$ } } }"; var expected = @"using System; class Program { static void Main() { switch (DayOfWeek.Monday) { case DayOfWeek.Monday: case DayOfWeek.Tuesday: break; case DayOfWeek.Wednesday: break; default: } } }"; await AutoFormatOnColonAsync( code, expected, SyntaxKind.SemicolonToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens1() { var code = @"class Program { static void Main(string[] args) { gl::$$ } }"; var expected = @"class Program { static void Main(string[] args) { gl:: } }"; await AutoFormatOnMarkerAsync( code, expected, SyntaxKind.ColonColonToken, SyntaxKind.OpenBraceToken); } [WpfFact] [WorkItem(542538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542538")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task MissingTokens2() { var code = @"class C { void M() { M(() => { }$$ } }"; var expected = @"class C { void M() { M(() => { } } }"; await AutoFormatOnCloseBraceAsync( code, expected, SyntaxKind.EqualsGreaterThanToken); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task UsingAlias() { var code = @"using Alias=System;$$"; var expected = @"using Alias = System;"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.UsingKeyword); } [WpfFact] [WorkItem(542953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542953")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public async Task NoLineChangeWithSyntaxError() { var code = @"struct Goo { public int member; } class Program{ void Main() { var f = new Goo { member;$$ } } }"; var expected = @"struct Goo { public int member; } class Program{ void Main() { var f = new Goo { member; } } }"; await AutoFormatOnSemicolonAsync( code, expected, SyntaxKind.OpenBraceToken); } [WpfTheory] [CombinatorialData] [WorkItem(620568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620568")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void SkippedTokens1(bool useTabs) { var code = @";$$*"; var expected = @";*"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor(bool useTabs) { var code = @"class C { int Prop { get ;$$ }"; var expected = @"class C { int Prop { get; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor2(bool useTabs) { var code = @"class C { int Prop { get; set ;$$ }"; var expected = @"class C { int Prop { get; set; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(530830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530830")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor3(bool useTabs) { var code = @"class C { int Prop { get; set ; }$$ }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(784674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/784674")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor4(bool useTabs) { var code = @"class C { int Prop { get;$$ } }"; var expected = @"class C { int Prop { get; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor5(bool useTabs) { var code = @"class C { int Prop { get; set ;$$ } }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor6(bool useTabs) { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(924469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/924469")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void AutoPropertyAccessor7(bool useTabs) { var code = @"class C { int Prop { get;set;$$} }"; var expected = @"class C { int Prop { get; set; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NestedUsingStatement(bool useTabs) { var code = @"class C { public void M() { using (null) using(null)$$ } }"; var expected = @"class C { public void M() { using (null) using (null) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NestedNotUsingStatement(bool useTabs) { var code = @"class C { public void M() { using (null) for(;;)$$ } }"; var expected = @"class C { public void M() { using (null) for(;;) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { using (null) fixed (void* ptr = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedCheckedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) checked { }$$ } }"; var expected = @"class C { public void M() { using (null) checked { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void UsingStatementWithNestedUncheckedStatement(bool useTabs) { var code = @"class C { public void M() { using (null) unchecked { }$$ } }"; var expected = @"class C { public void M() { using (null) unchecked { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedUsingStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr = &i) using (null)$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) using (null) } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr1 = &i) fixed (void* ptr2 = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FixedStatementWithNestedNotFixedStatement(bool useTabs) { var code = @"class C { public void M() { fixed (void* ptr = &i) if (false) { }$$ } }"; var expected = @"class C { public void M() { fixed (void* ptr = &i) if (false) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void NotFixedStatementWithNestedFixedStatement(bool useTabs) { var code = @"class C { public void M() { if (false) fixed (void* ptr = &i) { }$$ } }"; var expected = @"class C { public void M() { if (false) fixed (void* ptr = &i) { } } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstStatementOfBlock(bool useTabs) { var code = @"class C { public void M() {int s;$$ } }"; var expected = @"class C { public void M() { int s; } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMemberofType(bool useTabs) { var code = @"class C {int s;$$ public void M() { } }"; var expected = @"class C { int s; public void M() { } }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMethodMemberofType(bool useTabs) { var code = @"interface C {void s();$$ }"; var expected = @"interface C { void s(); }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForConstructor(bool useTabs) { var code = @"class C {public C()=>f=1;$$ }"; var expected = @"class C { public C() => f = 1; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForDestructor(bool useTabs) { var code = @"class C {~C()=>f=1;$$ }"; var expected = @"class C { ~C() => f = 1; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(17257, "https://github.com/dotnet/roslyn/issues/17257")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForOperator(bool useTabs) { var code = @"class C {public static C operator +(C left, C right)=>field=1;$$ static int field; }"; var expected = @"class C { public static C operator +(C left, C right) => field = 1; static int field; }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(954386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954386")] [Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)] public void FormattingRangeForFirstMemberOfNamespace(bool useTabs) { var code = @"namespace C {delegate void s();$$ }"; var expected = @"namespace C { delegate void s(); }"; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZero(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #if #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if # } } "; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZeroWithCode(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #if int s = 10; #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #if int s = 10; # } } "; AutoFormatToken(code, expected, useTabs); } [WpfTheory] [CombinatorialData] [WorkItem(981821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981821")] [Trait(Traits.Feature, Traits.Features.Formatting)] public void FormatDirectiveTriviaAlwaysToColumnZeroWithBrokenElseDirective(bool useTabs) { var code = @"class Program { static void Main(string[] args) { #else #$$ } } "; var expected = @"class Program { static void Main(string[] args) { #else # } } "; AutoFormatToken(code, expected, useTabs); } internal static void AutoFormatToken(string markup, string expected, bool useTabs) { if (useTabs) { markup = markup.Replace(" ", "\t"); expected = expected.Replace(" ", "\t"); } using var workspace = TestWorkspace.CreateCSharp(markup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var subjectDocument = workspace.Documents.Single(); var commandHandler = workspace.GetService<FormatCommandHandler>(); var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1); commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create()); var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot; Assert.Equal(expected, newSnapshot.GetText()); } private static Tuple<OptionSet, IEnumerable<AbstractFormattingRule>> GetService( TestWorkspace workspace) { var options = workspace.Options; return Tuple.Create(options, Formatter.GetDefaultFormattingRules(workspace, LanguageNames.CSharp)); } private static Task AutoFormatOnColonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.ColonToken, startTokenKind); private static Task AutoFormatOnSemicolonAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.SemicolonToken, startTokenKind); private static Task AutoFormatOnCloseBraceAsync(string codeWithMarker, string expected, SyntaxKind startTokenKind) => AutoFormatOnMarkerAsync(codeWithMarker, expected, SyntaxKind.CloseBraceToken, startTokenKind); private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, SyntaxKind tokenKind, SyntaxKind startTokenKind) { await AutoFormatOnMarkerAsync(initialMarkup, expected, useTabs: false, tokenKind, startTokenKind).ConfigureAwait(false); await AutoFormatOnMarkerAsync(initialMarkup.Replace(" ", "\t"), expected.Replace(" ", "\t"), useTabs: true, tokenKind, startTokenKind).ConfigureAwait(false); } private static async Task AutoFormatOnMarkerAsync(string initialMarkup, string expected, bool useTabs, SyntaxKind tokenKind, SyntaxKind startTokenKind) { using var workspace = TestWorkspace.CreateCSharp(initialMarkup); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, useTabs))); var tuple = GetService(workspace); var testDocument = workspace.Documents.Single(); var buffer = testDocument.GetTextBuffer(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(); var endToken = root.FindToken(position); if (position == endToken.SpanStart && !endToken.GetPreviousToken().IsKind(SyntaxKind.None)) { endToken = endToken.GetPreviousToken(); } Assert.Equal(tokenKind, endToken.Kind()); var formatter = new CSharpSmartTokenFormatter(tuple.Item1, tuple.Item2, root); var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken); if (tokenRange == null) { Assert.Equal(SyntaxKind.None, startTokenKind); return; } Assert.Equal(startTokenKind, tokenRange.Value.Item1.Kind()); if (tokenRange.Value.Item1.Equals(tokenRange.Value.Item2)) { return; } var changes = formatter.FormatRange(workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, CancellationToken.None); var actual = GetFormattedText(buffer, changes); Assert.Equal(expected, actual); } private static string GetFormattedText(ITextBuffer buffer, IList<TextChange> changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } return buffer.CurrentSnapshot.GetText(); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/Core/Portable/Symbols/IEventSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an event. /// </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 IEventSymbol : ISymbol { /// <summary> /// The type of the event. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the event. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if the event is a WinRT type event. /// </summary> bool IsWindowsRuntimeEvent { get; } /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? RemoveMethod { get; } /// <summary> /// The 'raise' accessor of the event. Null if there is no raise method. /// </summary> IMethodSymbol? RaiseMethod { get; } /// <summary> /// The original definition of the event. If the event is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IEventSymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden event, or null. /// </summary> IEventSymbol? OverriddenEvent { get; } /// <summary> /// Returns interface properties explicitly implemented by this event. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one event. /// </remarks> ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an event. /// </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 IEventSymbol : ISymbol { /// <summary> /// The type of the event. /// </summary> ITypeSymbol Type { get; } /// <summary> /// The top-level nullability of the event. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if the event is a WinRT type event. /// </summary> bool IsWindowsRuntimeEvent { get; } /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> IMethodSymbol? RemoveMethod { get; } /// <summary> /// The 'raise' accessor of the event. Null if there is no raise method. /// </summary> IMethodSymbol? RaiseMethod { get; } /// <summary> /// The original definition of the event. If the event is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IEventSymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden event, or null. /// </summary> IEventSymbol? OverriddenEvent { get; } /// <summary> /// Returns interface properties explicitly implemented by this event. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one event. /// </remarks> ImmutableArray<IEventSymbol> ExplicitInterfaceImplementations { get; } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Tools/IdeCoreBenchmarks/FindReferencesBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite) .WithChangedOption(StorageOptions.DatabaseMustSucceed, true))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite) .WithChangedOption(StorageOptions.DatabaseMustSucceed, true))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/Emit/ParameterTypeInformation.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.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class ParameterTypeInformation Implements Cci.IParameterTypeInformation Private ReadOnly _underlyingParameter As ParameterSymbol Public Sub New(underlyingParameter As ParameterSymbol) Debug.Assert(underlyingParameter IsNot Nothing) Me._underlyingParameter = underlyingParameter End Sub Private ReadOnly Property IParameterTypeInformationCustomModifiers As ImmutableArray(Of Cci.ICustomModifier) Implements Cci.IParameterTypeInformation.CustomModifiers Get Return _underlyingParameter.CustomModifiers.As(Of Cci.ICustomModifier) End Get End Property Private ReadOnly Property IParameterTypeInformationIsByReference As Boolean Implements Cci.IParameterTypeInformation.IsByReference Get Return _underlyingParameter.IsByRef End Get End Property Private ReadOnly Property IParameterTypeInformationRefCustomModifiers As ImmutableArray(Of Cci.ICustomModifier) Implements Cci.IParameterTypeInformation.RefCustomModifiers Get Return _underlyingParameter.RefCustomModifiers.As(Of Cci.ICustomModifier) End Get End Property Private Function IParameterTypeInformationGetType(context As EmitContext) As Cci.ITypeReference Implements Cci.IParameterTypeInformation.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Dim paramType As TypeSymbol = _underlyingParameter.Type Return moduleBeingBuilt.Translate(paramType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property IParameterListEntryIndex As UShort Implements Cci.IParameterListEntry.Index Get Return CType(_underlyingParameter.Ordinal, UShort) End Get End Property Public Overrides Function Equals(obj As Object) As Boolean ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function Public Overrides Function GetHashCode() As Integer ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class ParameterTypeInformation Implements Cci.IParameterTypeInformation Private ReadOnly _underlyingParameter As ParameterSymbol Public Sub New(underlyingParameter As ParameterSymbol) Debug.Assert(underlyingParameter IsNot Nothing) Me._underlyingParameter = underlyingParameter End Sub Private ReadOnly Property IParameterTypeInformationCustomModifiers As ImmutableArray(Of Cci.ICustomModifier) Implements Cci.IParameterTypeInformation.CustomModifiers Get Return _underlyingParameter.CustomModifiers.As(Of Cci.ICustomModifier) End Get End Property Private ReadOnly Property IParameterTypeInformationIsByReference As Boolean Implements Cci.IParameterTypeInformation.IsByReference Get Return _underlyingParameter.IsByRef End Get End Property Private ReadOnly Property IParameterTypeInformationRefCustomModifiers As ImmutableArray(Of Cci.ICustomModifier) Implements Cci.IParameterTypeInformation.RefCustomModifiers Get Return _underlyingParameter.RefCustomModifiers.As(Of Cci.ICustomModifier) End Get End Property Private Function IParameterTypeInformationGetType(context As EmitContext) As Cci.ITypeReference Implements Cci.IParameterTypeInformation.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Dim paramType As TypeSymbol = _underlyingParameter.Type Return moduleBeingBuilt.Translate(paramType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property IParameterListEntryIndex As UShort Implements Cci.IParameterListEntry.Index Get Return CType(_underlyingParameter.Ordinal, UShort) End Get End Property Public Overrides Function Equals(obj As Object) As Boolean ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function Public Overrides Function GetHashCode() As Integer ' It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. Throw Roslyn.Utilities.ExceptionUtilities.Unreachable End Function End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, enableIncremental:=False, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection Return New AdditionalSourcesCollection(".vb") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, enableIncremental:=False, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection Return New AdditionalSourcesCollection(".vb") End Function End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/Syntax/SyntaxKind.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Enumeration with all Visual Basic syntax node kinds. ''' </summary> Public Enum SyntaxKind As UShort ' ADD NEW SYNTAX TO THE END OF THIS ENUM OR YOU WILL BREAK BINARY COMPATIBILITY None = 0 List = GreenNode.ListKind ''' <summary> ''' A class to represent an empty statement. This can occur when a colon is on a ''' line without anything else. ''' </summary> EmptyStatement = 2 ' EmptyStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndIfStatement = 5 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndUsingStatement = 6 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndWithStatement = 7 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSelectStatement = 8 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndStructureStatement = 9 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndEnumStatement = 10 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndInterfaceStatement = 11 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndClassStatement = 12 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndModuleStatement = 13 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndNamespaceStatement = 14 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSubStatement = 15 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndFunctionStatement = 16 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndGetStatement = 17 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSetStatement = 18 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndPropertyStatement = 19 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndOperatorStatement = 20 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndEventStatement = 21 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndAddHandlerStatement = 22 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndRemoveHandlerStatement = 23 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndRaiseEventStatement = 24 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndWhileStatement = 25 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndTryStatement = 26 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSyncLockStatement = 27 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire source file of VB code. ''' </summary> CompilationUnit = 38 ' CompilationUnitSyntax ''' <summary> ''' Represents an Option statement, such as "Option Strict On". ''' </summary> OptionStatement = 41 ' OptionStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Imports statement, which has one or more imports clauses. ''' </summary> ImportsStatement = 42 ' ImportsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ' AliasImportsClause = 43 ' Removed. ''' <summary> ''' Represents the clause of an Imports statement that imports all members of a type or namespace or aliases a type or namespace. ''' </summary> SimpleImportsClause = 44 ' SimpleImportsClauseSyntax : ImportsClauseSyntax ''' <summary> ''' Defines a XML namespace for XML expressions. ''' </summary> XmlNamespaceImportsClause = 45 ' XmlNamespaceImportsClauseSyntax : ImportsClauseSyntax ''' <summary> ''' Represents a Namespace statement, its contents and the End Namespace statement. ''' </summary> NamespaceBlock = 48 ' NamespaceBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a namespace declaration. This node always ''' appears as the Begin of a BlockStatement with Kind=NamespaceBlock. ''' </summary> NamespaceStatement = 49 ' NamespaceStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of Module, its contents and the End statement that ''' ends it. ''' </summary> ModuleBlock = 50 ' ModuleBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Structure, its contents and the End statement ''' that ends it. ''' </summary> StructureBlock = 51 ' StructureBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Interface, its contents and the End statement ''' that ends it. ''' </summary> InterfaceBlock = 52 ' InterfaceBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Class its contents and the End statement that ''' ends it. ''' </summary> ClassBlock = 53 ' ClassBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of an Enum, its contents and the End Enum statement ''' that ends it. ''' </summary> EnumBlock = 54 ' EnumBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Inherits statement in a Class, Structure or Interface. ''' </summary> InheritsStatement = 57 ' InheritsStatementSyntax : InheritsOrImplementsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Implements statement in a Class or Structure. ''' </summary> ImplementsStatement = 58 ' ImplementsStatementSyntax : InheritsOrImplementsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Module declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=ModuleDeclarationBlock. ''' </summary> ModuleStatement = 59 ' ModuleStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Structure declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=StructureDeclarationBlock. ''' </summary> StructureStatement = 60 ' StructureStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Interface declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=InterfaceDeclarationBlock. ''' </summary> InterfaceStatement = 61 ' InterfaceStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Class declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=ClassDeclarationBlock. ''' </summary> ClassStatement = 62 ' ClassStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of an Enum declaration. This node always ''' appears as the Begin of an EnumBlock with Kind=EnumDeclarationBlock. ''' </summary> EnumStatement = 63 ' EnumStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the type parameter list in a declaration. ''' </summary> TypeParameterList = 66 ' TypeParameterListSyntax ''' <summary> ''' Represents a type parameter on a generic type declaration. ''' </summary> TypeParameter = 67 ' TypeParameterSyntax ''' <summary> ''' One of the type parameter constraints clauses. This represents a constraint ''' clause in the form of "As Constraint". ''' </summary> TypeParameterSingleConstraintClause = 70 ' TypeParameterSingleConstraintClauseSyntax : TypeParameterConstraintClauseSyntax ''' <summary> ''' One of the type parameter constraints clauses. This represents a constraint ''' clause in the form of "As { Constraints }". ''' </summary> TypeParameterMultipleConstraintClause = 71 ' TypeParameterMultipleConstraintClauseSyntax : TypeParameterConstraintClauseSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> NewConstraint = 72 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> ClassConstraint = 73 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> StructureConstraint = 74 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' Represents a type parameter constraint that is a type. ''' </summary> TypeConstraint = 75 ' TypeConstraintSyntax : ConstraintSyntax ''' <summary> ''' Represents a name and value in an EnumDeclarationBlock. ''' </summary> EnumMemberDeclaration = 78 ' EnumMemberDeclarationSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Function or Sub block declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> SubBlock = 79 ' MethodBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Function or Sub block declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> FunctionBlock = 80 ' MethodBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a constructor block declaration: A declaration that has a beginning ''' declaration, a body of executable statements and an end statement. ''' </summary> ConstructorBlock = 81 ' ConstructorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Operator block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> OperatorBlock = 82 ' OperatorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> GetAccessorBlock = 83 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> SetAccessorBlock = 84 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> AddHandlerAccessorBlock = 85 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> RemoveHandlerAccessorBlock = 86 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> RaiseEventAccessorBlock = 87 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a block property declaration: A declaration that has a beginning ''' declaration, some get or set accessor blocks and an end statement. ''' </summary> PropertyBlock = 88 ' PropertyBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a custom event declaration: A declaration that has a beginning event ''' declaration, some accessor blocks and an end statement. ''' </summary> EventBlock = 89 ' EventBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the parameter list in a method declaration. ''' </summary> ParameterList = 92 ' ParameterListSyntax ''' <summary> ''' The statement that declares a Sub or Function. If this method has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> SubStatement = 93 ' MethodStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' The statement that declares a Sub or Function. If this method has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> FunctionStatement = 94 ' MethodStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a constructor. This statement will be the Begin of a ''' BlockStatement with Kind=MethodDeclarationBlock, and the body of the method ''' will be the Body of that BlockStatement. ''' </summary> SubNewStatement = 95 ' SubNewStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A Declare statement that declares an external DLL method. ''' </summary> DeclareSubStatement = 96 ' DeclareStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A Declare statement that declares an external DLL method. ''' </summary> DeclareFunctionStatement = 97 ' DeclareStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a delegate type. ''' </summary> DelegateSubStatement = 98 ' DelegateStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a delegate type. ''' </summary> DelegateFunctionStatement = 99 ' DelegateStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares an event. If the event being declared is a custom ''' event, this statement will be the Begin of a PropertyOrEventBlock, and the ''' accessors will be part of the Accessors of that node. ''' </summary> EventStatement = 102 ' EventStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares an operator. If this operator has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> OperatorStatement = 103 ' OperatorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Statement that declares a property. If this property has accessors declared, ''' this statement will be the Begin of a BlockNode, and the accessors will be the ''' Body of that node. Auto properties are property declarations without a ''' PropertyBlock. ''' </summary> PropertyStatement = 104 ' PropertyStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> GetAccessorStatement = 105 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> SetAccessorStatement = 106 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> AddHandlerAccessorStatement = 107 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> RemoveHandlerAccessorStatement = 108 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> RaiseEventAccessorStatement = 111 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the "Implements ..." clause on a type member, which describes which ''' interface members this member implements. ''' </summary> ImplementsClause = 112 ' ImplementsClauseSyntax ''' <summary> ''' Represents the "Handles ..." clause on a method declaration that describes ''' which events this method handles. ''' </summary> HandlesClause = 113 ' HandlesClauseSyntax ''' <summary> ''' Represents event container specified through special keywords "Me", "MyBase" or ''' "MyClass".. ''' </summary> KeywordEventContainer = 114 ' KeywordEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents event container that refers to a WithEvents member. ''' </summary> WithEventsEventContainer = 115 ' WithEventsEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents event container that refers to a WithEvents member's property. ''' </summary> WithEventsPropertyEventContainer = 116 ' WithEventsPropertyEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents a single handled event in a "Handles ..." clause. ''' </summary> HandlesClauseItem = 117 ' HandlesClauseItemSyntax ''' <summary> ''' Represents the beginning of a declaration. However, not enough syntax is ''' detected to classify this as a field, method, property or event. This is node ''' always represents a syntax error. ''' </summary> IncompleteMember = 118 ' IncompleteMemberSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the declaration of one or more variables or constants, either as ''' local variables or as class/structure members. In the case of a constant, it is ''' represented by having "Const" in the Modifiers (although technically "Const" is ''' not a modifier, it is represented as one in the parse trees.) ''' </summary> FieldDeclaration = 119 ' FieldDeclarationSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the part of a variable or constant declaration statement that ''' associated one or more variable names with a type. ''' </summary> VariableDeclarator = 122 ' VariableDeclaratorSyntax ''' <summary> ''' Represents an "As {type-name}" clause that does not have an initializer or ''' "New". The type has optional attributes associated with it, although attributes ''' are not permitted in all possible places where this node occurs. ''' </summary> SimpleAsClause = 123 ' SimpleAsClauseSyntax : AsClauseSyntax ''' <summary> ''' Represents an "As New {type-name} [arguments] [initializers]" clause in a ''' declaration. The type has optional attributes associated with it, although ''' attributes are not permitted in many places where this node occurs (they are ''' permitted, for example, on automatically implemented properties.) ''' </summary> AsNewClause = 124 ' AsNewClauseSyntax : AsClauseSyntax ''' <summary> ''' Represents a "With {...} clause used to initialize a new object's members. ''' </summary> ObjectMemberInitializer = 125 ' ObjectMemberInitializerSyntax : ObjectCreationInitializerSyntax ''' <summary> ''' Represents a "From {...} clause used to initialize a new collection object's ''' elements. ''' </summary> ObjectCollectionInitializer = 126 ' ObjectCollectionInitializerSyntax : ObjectCreationInitializerSyntax ''' <summary> ''' Represent a field initializer in a With {...} initializer where the field name ''' is inferred from the initializer expression. ''' </summary> InferredFieldInitializer = 127 ' InferredFieldInitializerSyntax : FieldInitializerSyntax ''' <summary> ''' Represent a named field initializer in a With {...} initializer, such as ".x = ''' expr". ''' </summary> NamedFieldInitializer = 128 ' NamedFieldInitializerSyntax : FieldInitializerSyntax ''' <summary> ''' Represents an "= initializer" clause in a declaration for a variable, ''' parameter or automatic property. ''' </summary> EqualsValue = 129 ' EqualsValueSyntax ''' <summary> ''' Represent a parameter to a method, property, constructor, etc. ''' </summary> Parameter = 132 ' ParameterSyntax ''' <summary> ''' Represents an identifier with optional "?" or "()" or "(,,,)" modifiers, as ''' used in parameter declarations and variable declarations. ''' </summary> ModifiedIdentifier = 133 ' ModifiedIdentifierSyntax ''' <summary> ''' Represents a modifier that describes an array type, without bounds, such as ''' "()" or "(,)". ''' </summary> ArrayRankSpecifier = 134 ' ArrayRankSpecifierSyntax ''' <summary> ''' Represents a group of attributes within "&lt;" and "&gt;" brackets. ''' </summary> AttributeList = 135 ' AttributeListSyntax ''' <summary> ''' Represents a single attribute declaration within an attribute list. ''' </summary> Attribute = 136 ' AttributeSyntax ''' <summary> ''' Represents a single attribute declaration within an attribute list. ''' </summary> AttributeTarget = 137 ' AttributeTargetSyntax ''' <summary> ''' Represents a file-level attribute, in which the attributes have no other ''' syntactic element they are attached to. ''' </summary> AttributesStatement = 138 ' AttributesStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represent an expression in a statement context. This may only be a invocation ''' or await expression in standard code but may be any expression in VB ''' Interactive code. ''' </summary> ExpressionStatement = 139 ' ExpressionStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a "? expression" "Print" statement in VB Interactive code. ''' </summary> PrintStatement = 140 ' PrintStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a While...End While statement, including the While, body and End ''' While. ''' </summary> WhileBlock = 141 ' WhileBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire Using...End Using statement, including the Using, body and ''' End Using statements. ''' </summary> UsingBlock = 144 ' UsingBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a entire SyncLock...End SyncLock block, including the SyncLock ''' statement, the enclosed statements, and the End SyncLock statement. ''' </summary> SyncLockBlock = 145 ' SyncLockBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a With...End With block, include the With statement, the body of the ''' block and the End With statement. ''' </summary> WithBlock = 146 ' WithBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents the declaration of one or more local variables or constants. ''' </summary> LocalDeclarationStatement = 147 ' LocalDeclarationStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a label statement. ''' </summary> LabelStatement = 148 ' LabelStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "GoTo" statement. ''' </summary> GoToStatement = 149 ' GoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> IdentifierLabel = 150 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> NumericLabel = 151 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> NextLabel = 152 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' Represents a "Stop" or "End" statement. The Kind can be used to determine which ''' kind of statement this is. ''' </summary> StopStatement = 153 ' StopOrEndStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Stop" or "End" statement. The Kind can be used to determine which ''' kind of statement this is. ''' </summary> EndStatement = 156 ' StopOrEndStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitDoStatement = 157 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitForStatement = 158 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitSubStatement = 159 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitFunctionStatement = 160 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitOperatorStatement = 161 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitPropertyStatement = 162 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitTryStatement = 163 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitSelectStatement = 164 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitWhileStatement = 165 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueWhileStatement = 166 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueDoStatement = 167 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueForStatement = 168 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Return" statement. ''' </summary> ReturnStatement = 169 ' ReturnStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a line If-Then-Else statement. ''' </summary> SingleLineIfStatement = 170 ' SingleLineIfStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents part of a single line If statement, consisting of a beginning ''' if-statement, followed by a body of statement controlled by that beginning ''' statement. The Kind property returns if this is a SingleLineIf. ''' </summary> SingleLineIfPart = 171 ' SingleLineIfPartSyntax ''' <summary> ''' Represents the Else part of an If statement, consisting of a Else statement, ''' followed by a body of statement controlled by that Else. ''' </summary> SingleLineElseClause = 172 ' SingleLineElseClauseSyntax ''' <summary> ''' Represents a block If...Then...Else...EndIf Statement. The Kind property can be ''' used to determine if it is a block or line If. ''' </summary> MultiLineIfBlock = 173 ' MultiLineIfBlockSyntax : ExecutableStatementSyntax : StatementSyntax ' IfPart = 179 ' This node was removed. ''' <summary> ''' Represents part of an If statement, consisting of a beginning statement (If or ''' ElseIf), followed by a body of statement controlled by that beginning ''' statement. The Kind property returns if this is an If or ElseIf. ''' </summary> ElseIfBlock = 180 ' ElseIfBlockSyntax ''' <summary> ''' Represents the Else part of an If statement, consisting of a Else statement, ''' followed by a body of statement controlled by that Else. ''' </summary> ElseBlock = 181 ' ElseBlockSyntax ''' <summary> ''' Represents the If part or ElseIf part of a If...End If block (or line If). This ''' statement is always the Begin of a IfPart. The Kind can be examined to ''' determine if this is an If or an ElseIf statement. ''' </summary> IfStatement = 182 ' IfStatementSyntax : StatementSyntax ''' <summary> ''' Represents the If part or ElseIf part of a If...End If block (or line If). This ''' statement is always the Begin of a IfPart. The Kind can be examined to ''' determine if this is an If or an ElseIf statement. ''' </summary> ElseIfStatement = 183 ' IfStatementSyntax : StatementSyntax ''' <summary> ''' Represents the Else part of a If...End If block (or line If). This statement is ''' always the Begin of a ElsePart. ''' </summary> ElseStatement = 184 ' ElseStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire Try...Catch...Finally...End Try statement. ''' </summary> TryBlock = 185 ' TryBlockSyntax : ExecutableStatementSyntax : StatementSyntax ' TryPart = 186 ' This node was removed. ''' <summary> ''' Represents a Catch part of a Try...Catch...Finally...End Try statement, ''' consisting of a Catch statement, followed by a body of statements controlled by ''' that Catch statement. The Kind property returns which kind of part this is. ''' </summary> CatchBlock = 187 ' CatchBlockSyntax ''' <summary> ''' Represents the Finally part of a Try...Catch...Finally...End Try statement, ''' consisting of a Finally statement, followed by a body of statements controlled ''' by the Finally. ''' </summary> FinallyBlock = 188 ' FinallyBlockSyntax ''' <summary> ''' Represents the Try part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a TryPart. ''' </summary> TryStatement = 189 ' TryStatementSyntax : StatementSyntax ''' <summary> ''' Represents the Catch part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a CatchPart. ''' </summary> CatchStatement = 190 ' CatchStatementSyntax : StatementSyntax ''' <summary> ''' Represents the When/Filter clause of a Catch statement ''' </summary> CatchFilterClause = 191 ' CatchFilterClauseSyntax ''' <summary> ''' Represents the Finally part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a FinallyPart. ''' </summary> FinallyStatement = 194 ' FinallyStatementSyntax : StatementSyntax ''' <summary> ''' Represents the "Error" statement. ''' </summary> ErrorStatement = 195 ' ErrorStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToZeroStatement = 196 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToMinusOneStatement = 197 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToLabelStatement = 198 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Resume Next statement. ''' </summary> OnErrorResumeNextStatement = 199 ' OnErrorResumeNextStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeStatement = 200 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeLabelStatement = 201 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeNextStatement = 202 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Select Case block, including the Select Case that begins it, the ''' contains Case blocks and the End Select. ''' </summary> SelectBlock = 203 ' SelectBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Select Case statement. This statement always occurs as the Begin ''' of a SelectBlock. ''' </summary> SelectStatement = 204 ' SelectStatementSyntax : StatementSyntax ''' <summary> ''' Represents a case statement and its subsequent block. ''' </summary> CaseBlock = 207 ' CaseBlockSyntax ''' <summary> ''' Represents a case statement and its subsequent block. ''' </summary> CaseElseBlock = 210 ' CaseBlockSyntax ''' <summary> ''' Represents a Case or Case Else statement. This statement is always the Begin of ''' a CaseBlock. If this is a Case Else statement, the Kind=CaseElse, otherwise the ''' Kind=Case. ''' </summary> CaseStatement = 211 ' CaseStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Case or Case Else statement. This statement is always the Begin of ''' a CaseBlock. If this is a Case Else statement, the Kind=CaseElse, otherwise the ''' Kind=Case. ''' </summary> CaseElseStatement = 212 ' CaseStatementSyntax : StatementSyntax ''' <summary> ''' The "Else" part in a Case Else statement. ''' </summary> ElseCaseClause = 213 ' ElseCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a single value in a Case. ''' </summary> SimpleCaseClause = 214 ' SimpleCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a range "expression To expression" in a Case. ''' </summary> RangeCaseClause = 215 ' RangeCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseEqualsClause = 216 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseNotEqualsClause = 217 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseLessThanClause = 218 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseLessThanOrEqualClause = 219 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseGreaterThanOrEqualClause = 222 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseGreaterThanClause = 223 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents the "SyncLock" statement. This statement always occurs as the Begin ''' of a SyncLockBlock. ''' </summary> SyncLockStatement = 226 ' SyncLockStatementSyntax : StatementSyntax 'DoLoopTopTestBlock = 227 'Removed 'DoLoopBottomTestBlock = 228 'Removed 'DoLoopForeverBlock = 229 'Removed 'DoStatement = 230 'Removed 'LoopStatement = 231 'Removed 'WhileClause = 232 'Removed 'UntilClause = 233 'Removed WhileStatement = 234 ' WhileStatementSyntax : StatementSyntax ''' <summary> ''' Represents a For or For Each block, including the introducing statement, the ''' body and the "Next" (which can be omitted if a containing For has a Next with ''' multiple variables). ''' </summary> ForBlock = 237 ' ForBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a For or For Each block, including the introducing statement, the ''' body and the "Next" (which can be omitted if a containing For has a Next with ''' multiple variables). ''' </summary> ForEachBlock = 238 ' ForBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' The For statement that begins a For-Next block. This statement always occurs as ''' the Begin of a ForBlock. Most of the time, the End of that ForBlock is the ''' corresponding Next statement. However, multiple nested For statements are ended ''' by a single Next statement with multiple variables, then the inner For ''' statements will have End set to Nothing, and the Next statement is the End of ''' the outermost For statement that is being ended. ''' </summary> ForStatement = 239 ' ForStatementSyntax : StatementSyntax ''' <summary> ''' The Step clause in a For Statement. ''' </summary> ForStepClause = 240 ' ForStepClauseSyntax ''' <summary> ''' The For Each statement that begins a For Each-Next block. This statement always ''' occurs as the Begin of a ForBlock, and the body of the For Each-Next is the ''' Body of that ForBlock. Most of the time, the End of that ForBlock is the ''' corresponding Next statement. However, multiple nested For statements are ended ''' by a single Next statement with multiple variables, then the inner For ''' statements will have End set to Nothing, and the Next statement is the End of ''' the outermost For statement that is being ended. ''' </summary> ForEachStatement = 241 ' ForEachStatementSyntax : StatementSyntax ''' <summary> ''' The Next statement that ends a For-Next or For Each-Next block. This statement ''' always occurs as the End of a ForBlock (with Kind=ForBlock or ForEachBlock), ''' and the body of the For-Next is the Body of that ForBlock. The Begin of that ''' ForBlock has the corresponding For or For Each statement. ''' </summary> NextStatement = 242 ' NextStatementSyntax : StatementSyntax ''' <summary> ''' The Using statement that begins a Using block. This statement always occurs as ''' the Begin of a UsingBlock, and the body of the Using is the Body of that ''' UsingBlock. ''' </summary> UsingStatement = 243 ' UsingStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Throw statement. ''' </summary> ThrowStatement = 246 ' ThrowStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> SimpleAssignmentStatement = 247 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> MidAssignmentStatement = 248 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> AddAssignmentStatement = 249 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> SubtractAssignmentStatement = 250 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> MultiplyAssignmentStatement = 251 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> DivideAssignmentStatement = 252 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> IntegerDivideAssignmentStatement = 253 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> ExponentiateAssignmentStatement = 254 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> LeftShiftAssignmentStatement = 255 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> RightShiftAssignmentStatement = 258 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> ConcatenateAssignmentStatement = 259 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a left-hand side of a MidAssignment statement. ''' </summary> MidExpression = 260 ' MidExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represent a call statement (also known as a invocation statement). ''' </summary> CallStatement = 261 ' CallStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an AddHandler or RemoveHandler statement. The Kind property ''' determines which one. ''' </summary> AddHandlerStatement = 262 ' AddRemoveHandlerStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an AddHandler or RemoveHandler statement. The Kind property ''' determines which one. ''' </summary> RemoveHandlerStatement = 263 ' AddRemoveHandlerStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a RaiseEvent statement. ''' </summary> RaiseEventStatement = 264 ' RaiseEventStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "With" statement. This statement always occurs as the ''' BeginStatement of a WithBlock, and the body of the With is the Body of that ''' WithBlock. ''' </summary> WithStatement = 265 ' WithStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement. ''' </summary> ReDimStatement = 266 ' ReDimStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement. ''' </summary> ReDimPreserveStatement = 267 ' ReDimStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement clause. ''' </summary> RedimClause = 270 ' RedimClauseSyntax ''' <summary> ''' Represents an "Erase" statement. ''' </summary> EraseStatement = 271 ' EraseStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> CharacterLiteralExpression = 272 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> TrueLiteralExpression = 273 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> FalseLiteralExpression = 274 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> NumericLiteralExpression = 275 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> DateLiteralExpression = 276 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> StringLiteralExpression = 279 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> NothingLiteralExpression = 280 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a parenthesized expression. ''' </summary> ParenthesizedExpression = 281 ' ParenthesizedExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "Me" ''' </summary> MeExpression = 282 ' MeExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "MyBase" ''' </summary> MyBaseExpression = 283 ' MyBaseExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "MyClass" ''' </summary> MyClassExpression = 284 ' MyClassExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a GetType expression. ''' </summary> GetTypeExpression = 285 ' GetTypeExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a TypeOf...Is or IsNot expression. ''' </summary> TypeOfIsExpression = 286 ' TypeOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a TypeOf...Is or IsNot expression. ''' </summary> TypeOfIsNotExpression = 287 ' TypeOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a GetXmlNamespace expression. ''' </summary> GetXmlNamespaceExpression = 290 ' GetXmlNamespaceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents member access (.name) or dictionary access (!name). The Kind ''' property determines which kind of access. ''' </summary> SimpleMemberAccessExpression = 291 ' MemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents member access (.name) or dictionary access (!name). The Kind ''' property determines which kind of access. ''' </summary> DictionaryAccessExpression = 292 ' MemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlElementAccessExpression = 293 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlDescendantAccessExpression = 294 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlAttributeAccessExpression = 295 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an invocation expression consisting of an invocation target and an ''' optional argument list or an array, parameterized property or object default ''' property index. ''' </summary> InvocationExpression = 296 ' InvocationExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a New expression that creates a new non-array object, possibly with ''' a "With" or "From" clause. ''' </summary> ObjectCreationExpression = 297 ' ObjectCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a New expression that create an object of anonymous type. ''' </summary> AnonymousObjectCreationExpression = 298 ' AnonymousObjectCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an expression that creates a new array. ''' </summary> ArrayCreationExpression = 301 ' ArrayCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an expression that creates a new array without naming the element ''' type. ''' </summary> CollectionInitializer = 302 ' CollectionInitializerSyntax : ExpressionSyntax CTypeExpression = 303 ' CTypeExpressionSyntax : CastExpressionSyntax : ExpressionSyntax DirectCastExpression = 304 ' DirectCastExpressionSyntax : CastExpressionSyntax : ExpressionSyntax TryCastExpression = 305 ' TryCastExpressionSyntax : CastExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a cast to a pre-defined type using a pre-defined cast expression, ''' such as CInt or CLng. ''' </summary> PredefinedCastExpression = 306 ' PredefinedCastExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AddExpression = 307 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> SubtractExpression = 308 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> MultiplyExpression = 309 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> DivideExpression = 310 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IntegerDivideExpression = 311 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ExponentiateExpression = 314 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LeftShiftExpression = 315 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> RightShiftExpression = 316 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ConcatenateExpression = 317 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ModuloExpression = 318 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> EqualsExpression = 319 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> NotEqualsExpression = 320 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LessThanExpression = 321 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LessThanOrEqualExpression = 322 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> GreaterThanOrEqualExpression = 323 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> GreaterThanExpression = 324 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IsExpression = 325 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IsNotExpression = 326 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LikeExpression = 327 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> OrExpression = 328 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ExclusiveOrExpression = 329 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AndExpression = 330 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> OrElseExpression = 331 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AndAlsoExpression = 332 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> UnaryPlusExpression = 333 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> UnaryMinusExpression = 334 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> NotExpression = 335 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> AddressOfExpression = 336 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a conditional expression, If(condition, true-expr, false-expr) or ''' If(expr, nothing-expr). ''' </summary> BinaryConditionalExpression = 337 ' BinaryConditionalExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a conditional expression, If(condition, true-expr, false-expr) or ''' If(expr, nothing-expr). ''' </summary> TernaryConditionalExpression = 338 ' TernaryConditionalExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single line lambda expression. ''' </summary> SingleLineFunctionLambdaExpression = 339 ' SingleLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single line lambda expression. ''' </summary> SingleLineSubLambdaExpression = 342 ' SingleLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a multi-line lambda expression. ''' </summary> MultiLineFunctionLambdaExpression = 343 ' MultiLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a multi-line lambda expression. ''' </summary> MultiLineSubLambdaExpression = 344 ' MultiLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents the header part of a lambda expression ''' </summary> SubLambdaHeader = 345 ' LambdaHeaderSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the header part of a lambda expression ''' </summary> FunctionLambdaHeader = 346 ' LambdaHeaderSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a parenthesized argument list. ''' </summary> ArgumentList = 347 ' ArgumentListSyntax ''' <summary> ''' Represents an omitted argument in an argument list. An omitted argument is not ''' considered a syntax error but a valid case when no argument is required. ''' </summary> OmittedArgument = 348 ' OmittedArgumentSyntax : ArgumentSyntax ''' <summary> ''' Represents an argument that is just an optional argument name and an expression. ''' </summary> SimpleArgument = 349 ' SimpleArgumentSyntax : ArgumentSyntax ' NamedArgument = 350 ' Removed ''' <summary> ''' Represents a range argument, such as "0 to 5", used in array bounds. The ''' "Value" property represents the upper bound of the range. ''' </summary> RangeArgument = 351 ' RangeArgumentSyntax : ArgumentSyntax ''' <summary> ''' This class represents a query expression. A query expression is composed of one ''' or more query operators in a row. The first query operator must be a From or ''' Aggregate. ''' </summary> QueryExpression = 352 ' QueryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a single variable of the form "x [As Type] In expression" for use in ''' query expressions. ''' </summary> CollectionRangeVariable = 353 ' CollectionRangeVariableSyntax ''' <summary> ''' Describes a single variable of the form "[x [As Type] =] expression" for use in ''' query expressions. ''' </summary> ExpressionRangeVariable = 354 ' ExpressionRangeVariableSyntax ''' <summary> ''' Describes a single variable of the form "[x [As Type] =] aggregation-function" ''' for use in the Into clause of Aggregate or Group By or Group Join query ''' operators. ''' </summary> AggregationRangeVariable = 355 ' AggregationRangeVariableSyntax ''' <summary> ''' Represents the name and optional type of an expression range variable. ''' </summary> VariableNameEquals = 356 ' VariableNameEqualsSyntax ''' <summary> ''' Represents an invocation of an Aggregation function in the aggregation range ''' variable declaration of a Group By, Group Join or Aggregate query operator. ''' </summary> FunctionAggregation = 357 ' FunctionAggregationSyntax : AggregationSyntax : ExpressionSyntax ''' <summary> ''' Represents the use of "Group" as the aggregation function in the in the ''' aggregation range variable declaration of a Group By or Group Join query ''' operator. ''' </summary> GroupAggregation = 358 ' GroupAggregationSyntax : AggregationSyntax : ExpressionSyntax ''' <summary> ''' Represents a "From" query operator. If this is the beginning of a query, the ''' Source will be Nothing. Otherwise, the Source will be the part of the query to ''' the left of the From. ''' </summary> FromClause = 359 ' FromClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Let" query operator. ''' </summary> LetClause = 360 ' LetClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents an Aggregate query operator. ''' </summary> AggregateClause = 361 ' AggregateClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Distinct" query operator. ''' </summary> DistinctClause = 362 ' DistinctClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Where" query operator. ''' </summary> WhereClause = 363 ' WhereClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip While" or "Take While" query operator. The Kind property ''' tells which. ''' </summary> SkipWhileClause = 364 ' PartitionWhileClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip While" or "Take While" query operator. The Kind property ''' tells which. ''' </summary> TakeWhileClause = 365 ' PartitionWhileClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip" or "Take" query operator. The Kind property tells which. ''' </summary> SkipClause = 366 ' PartitionClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip" or "Take" query operator. The Kind property tells which. ''' </summary> TakeClause = 367 ' PartitionClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Group By" query operator. ''' </summary> GroupByClause = 368 ' GroupByClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "expression Equals expression" condition in a Join. ''' </summary> JoinCondition = 369 ' JoinConditionSyntax ''' <summary> ''' Represents a Join query operator. ''' </summary> SimpleJoinClause = 370 ' SimpleJoinClauseSyntax : JoinClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Group Join" query operator. ''' </summary> GroupJoinClause = 371 ' GroupJoinClauseSyntax : JoinClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Order By" query operator. ''' </summary> OrderByClause = 372 ' OrderByClauseSyntax : QueryClauseSyntax ''' <summary> ''' An expression to order by, plus an optional ordering. The Kind indicates ''' whether to order in ascending or descending order. ''' </summary> AscendingOrdering = 375 ' OrderingSyntax ''' <summary> ''' An expression to order by, plus an optional ordering. The Kind indicates ''' whether to order in ascending or descending order. ''' </summary> DescendingOrdering = 376 ' OrderingSyntax ''' <summary> ''' Represents the "Select" query operator. ''' </summary> SelectClause = 377 ' SelectClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents an XML Document literal expression. ''' </summary> XmlDocument = 378 ' XmlDocumentSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the XML declaration prologue in an XML literal expression. ''' </summary> XmlDeclaration = 379 ' XmlDeclarationSyntax ''' <summary> ''' Represents an XML document prologue option - version, encoding, standalone or ''' whitespace in an XML literal expression. ''' </summary> XmlDeclarationOption = 380 ' XmlDeclarationOptionSyntax ''' <summary> ''' Represents an XML element with content in an XML literal expression. ''' </summary> XmlElement = 381 ' XmlElementSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents Xml text. ''' </summary> XmlText = 382 ' XmlTextSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the start tag of an XML element of the form &lt;element&gt;. ''' </summary> XmlElementStartTag = 383 ' XmlElementStartTagSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the end tag of an XML element of the form &lt;/element&gt;. ''' </summary> XmlElementEndTag = 384 ' XmlElementEndTagSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an empty XML element of the form &lt;element /&gt; ''' </summary> XmlEmptyElement = 385 ' XmlEmptyElementSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML attribute in an XML literal expression. ''' </summary> XmlAttribute = 386 ' XmlAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents a string of XML characters embedded as the content of an XML ''' element. ''' </summary> XmlString = 387 ' XmlStringSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form 'name' appearing in GetXmlNamespace(). ''' </summary> XmlPrefixName = 388 ' XmlPrefixNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form 'name' or 'namespace:name' appearing in ''' source as part of an XML literal or member access expression or an XML ''' namespace import clause. ''' </summary> XmlName = 389 ' XmlNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form &lt;xml-name&gt; appearing in source as part ''' of an XML literal or member access expression or an XML namespace import ''' clause. ''' </summary> XmlBracketedName = 390 ' XmlBracketedNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML namespace prefix of the form 'prefix:' as in xml:ns="". ''' </summary> XmlPrefix = 391 ' XmlPrefixSyntax ''' <summary> ''' Represents an XML comment of the form &lt;!-- Comment --&gt; appearing in an ''' XML literal expression. ''' </summary> XmlComment = 392 ' XmlCommentSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML processing instruction of the form '&lt;? XMLProcessingTarget ''' XMLProcessingValue ?&gt;'. ''' </summary> XmlProcessingInstruction = 393 ' XmlProcessingInstructionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML CDATA section in an XML literal expression. ''' </summary> XmlCDataSection = 394 ' XmlCDataSectionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an embedded expression in an XML literal e.g. '&lt;name&gt;&lt;%= ''' obj.Name =%&gt;&lt;/name&gt;'. ''' </summary> XmlEmbeddedExpression = 395 ' XmlEmbeddedExpressionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an array type, such as "A() or "A(,)", without bounds specified for ''' the array. ''' </summary> ArrayType = 396 ' ArrayTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' A type name that represents a nullable type, such as "Integer?". ''' </summary> NullableType = 397 ' NullableTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents an occurrence of a Visual Basic built-in type such as Integer or ''' String in source code. ''' </summary> PredefinedType = 398 ' PredefinedTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a type name consisting of a single identifier (which might include ''' brackets or a type character). ''' </summary> IdentifierName = 399 ' IdentifierNameSyntax : SimpleNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a simple type name with one or more generic arguments, such as "X(Of ''' Y, Z). ''' </summary> GenericName = 400 ' GenericNameSyntax : SimpleNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a qualified type name, for example X.Y or X(Of Z).Y. ''' </summary> QualifiedName = 401 ' QualifiedNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a name in the global namespace. ''' </summary> GlobalName = 402 ' GlobalNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a parenthesized list of generic type arguments. ''' </summary> TypeArgumentList = 403 ' TypeArgumentListSyntax ''' <summary> ''' Syntax node class that represents a value of 'cref' attribute inside ''' documentation comment trivia. ''' </summary> CrefReference = 404 ' CrefReferenceSyntax ''' <summary> ''' Represents a parenthesized list of argument types for a signature inside ''' CrefReferenceSyntax syntax. ''' </summary> CrefSignature = 407 ' CrefSignatureSyntax CrefSignaturePart = 408 ' CrefSignaturePartSyntax CrefOperatorReference = 409 ' CrefOperatorReferenceSyntax : NameSyntax : TypeSyntax : ExpressionSyntax QualifiedCrefOperatorReference = 410 ' QualifiedCrefOperatorReferenceSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represent a Yield statement. ''' </summary> YieldStatement = 411 ' YieldStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a Await expression. ''' </summary> AwaitExpression = 412 ' AwaitExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AddHandlerKeyword = 413 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AddressOfKeyword = 414 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AliasKeyword = 415 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AndKeyword = 416 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AndAlsoKeyword = 417 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AsKeyword = 418 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> BooleanKeyword = 421 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByRefKeyword = 422 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByteKeyword = 423 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByValKeyword = 424 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CallKeyword = 425 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CaseKeyword = 426 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CatchKeyword = 427 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CBoolKeyword = 428 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CByteKeyword = 429 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CCharKeyword = 432 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDateKeyword = 433 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDecKeyword = 434 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDblKeyword = 435 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CharKeyword = 436 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CIntKeyword = 437 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ClassKeyword = 438 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CLngKeyword = 439 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CObjKeyword = 440 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ConstKeyword = 441 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReferenceKeyword = 442 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ContinueKeyword = 443 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CSByteKeyword = 444 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CShortKeyword = 445 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CSngKeyword = 446 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CStrKeyword = 447 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CTypeKeyword = 448 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CUIntKeyword = 449 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CULngKeyword = 450 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CUShortKeyword = 453 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DateKeyword = 454 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DecimalKeyword = 455 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DeclareKeyword = 456 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DefaultKeyword = 457 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DelegateKeyword = 458 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DimKeyword = 459 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DirectCastKeyword = 460 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DoKeyword = 461 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DoubleKeyword = 462 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EachKeyword = 463 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ElseKeyword = 464 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ElseIfKeyword = 465 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EndKeyword = 466 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EnumKeyword = 467 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EraseKeyword = 468 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ErrorKeyword = 469 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EventKeyword = 470 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExitKeyword = 471 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FalseKeyword = 474 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FinallyKeyword = 475 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ForKeyword = 476 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FriendKeyword = 477 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FunctionKeyword = 478 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetKeyword = 479 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetTypeKeyword = 480 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetXmlNamespaceKeyword = 481 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GlobalKeyword = 482 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GoToKeyword = 483 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> HandlesKeyword = 484 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IfKeyword = 485 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ImplementsKeyword = 486 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ImportsKeyword = 487 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InKeyword = 488 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InheritsKeyword = 489 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IntegerKeyword = 490 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InterfaceKeyword = 491 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsKeyword = 492 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsNotKeyword = 495 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LetKeyword = 496 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LibKeyword = 497 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LikeKeyword = 498 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LongKeyword = 499 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LoopKeyword = 500 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MeKeyword = 501 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ModKeyword = 502 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ModuleKeyword = 503 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MustInheritKeyword = 504 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MustOverrideKeyword = 505 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MyBaseKeyword = 506 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MyClassKeyword = 507 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NamespaceKeyword = 508 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NarrowingKeyword = 509 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NextKeyword = 510 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NewKeyword = 511 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotKeyword = 512 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NothingKeyword = 513 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotInheritableKeyword = 516 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotOverridableKeyword = 517 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ObjectKeyword = 518 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OfKeyword = 519 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OnKeyword = 520 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OperatorKeyword = 521 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OptionKeyword = 522 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OptionalKeyword = 523 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrKeyword = 524 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrElseKeyword = 525 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverloadsKeyword = 526 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverridableKeyword = 527 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverridesKeyword = 528 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ParamArrayKeyword = 529 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PartialKeyword = 530 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PrivateKeyword = 531 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PropertyKeyword = 532 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ProtectedKeyword = 533 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PublicKeyword = 534 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RaiseEventKeyword = 537 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReadOnlyKeyword = 538 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReDimKeyword = 539 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> REMKeyword = 540 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RemoveHandlerKeyword = 541 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ResumeKeyword = 542 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReturnKeyword = 543 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SByteKeyword = 544 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SelectKeyword = 545 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SetKeyword = 546 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ShadowsKeyword = 547 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SharedKeyword = 548 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ShortKeyword = 549 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SingleKeyword = 550 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StaticKeyword = 551 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StepKeyword = 552 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StopKeyword = 553 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StringKeyword = 554 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StructureKeyword = 555 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SubKeyword = 558 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SyncLockKeyword = 559 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ThenKeyword = 560 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ThrowKeyword = 561 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ToKeyword = 562 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TrueKeyword = 563 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TryKeyword = 564 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TryCastKeyword = 565 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TypeOfKeyword = 566 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UIntegerKeyword = 567 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ULongKeyword = 568 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UShortKeyword = 569 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UsingKeyword = 570 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhenKeyword = 571 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhileKeyword = 572 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WideningKeyword = 573 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WithKeyword = 574 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WithEventsKeyword = 575 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WriteOnlyKeyword = 578 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> XorKeyword = 579 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EndIfKeyword = 580 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GosubKeyword = 581 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> VariantKeyword = 582 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WendKeyword = 583 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AggregateKeyword = 584 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AllKeyword = 585 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AnsiKeyword = 586 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AscendingKeyword = 587 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AssemblyKeyword = 588 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AutoKeyword = 589 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> BinaryKeyword = 590 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByKeyword = 591 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CompareKeyword = 592 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CustomKeyword = 593 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DescendingKeyword = 594 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DisableKeyword = 595 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DistinctKeyword = 596 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EnableKeyword = 599 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EqualsKeyword = 600 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExplicitKeyword = 601 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExternalSourceKeyword = 602 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExternalChecksumKeyword = 603 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FromKeyword = 604 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GroupKeyword = 605 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InferKeyword = 606 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IntoKeyword = 607 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsFalseKeyword = 608 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsTrueKeyword = 609 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> JoinKeyword = 610 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> KeyKeyword = 611 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MidKeyword = 612 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OffKeyword = 613 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrderKeyword = 614 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OutKeyword = 615 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PreserveKeyword = 616 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RegionKeyword = 617 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SkipKeyword = 620 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StrictKeyword = 621 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TakeKeyword = 622 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TextKeyword = 623 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UnicodeKeyword = 624 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UntilKeyword = 625 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WarningKeyword = 626 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhereKeyword = 627 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TypeKeyword = 628 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> XmlKeyword = 629 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AsyncKeyword = 630 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AwaitKeyword = 631 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IteratorKeyword = 632 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> YieldKeyword = 633 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ExclamationToken = 634 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AtToken = 635 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CommaToken = 636 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> HashToken = 637 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AmpersandToken = 638 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SingleQuoteToken = 641 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> OpenParenToken = 642 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CloseParenToken = 643 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> OpenBraceToken = 644 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CloseBraceToken = 645 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SemicolonToken = 646 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AsteriskToken = 647 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PlusToken = 648 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusToken = 649 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> DotToken = 650 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashToken = 651 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ColonToken = 652 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanToken = 653 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanEqualsToken = 654 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanGreaterThanToken = 655 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EqualsToken = 656 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanToken = 657 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanEqualsToken = 658 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BackslashToken = 659 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CaretToken = 662 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ColonEqualsToken = 663 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AmpersandEqualsToken = 664 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AsteriskEqualsToken = 665 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PlusEqualsToken = 666 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusEqualsToken = 667 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashEqualsToken = 668 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BackslashEqualsToken = 669 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CaretEqualsToken = 670 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanLessThanToken = 671 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanGreaterThanToken = 672 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanLessThanEqualsToken = 673 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanGreaterThanEqualsToken = 674 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> QuestionToken = 675 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> DoubleQuoteToken = 676 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> StatementTerminatorToken = 677 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndOfFileToken = 678 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EmptyToken = 679 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashGreaterThanToken = 680 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanSlashToken = 683 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanExclamationMinusMinusToken = 684 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusMinusGreaterThanToken = 685 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanQuestionToken = 686 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> QuestionGreaterThanToken = 687 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanPercentEqualsToken = 688 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PercentGreaterThanToken = 689 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BeginCDataToken = 690 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndCDataToken = 691 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndOfXmlToken = 692 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a sequence of characters appearing in source with no possible ''' meaning in the Visual Basic language (e.g. the semicolon ';'). This token ''' should only appear in SkippedTokenTrivia as an artifact of parsing error ''' recovery. ''' </summary> BadToken = 693 ' BadTokenSyntax : PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents an Xml NCName per Namespaces in XML 1.0 ''' </summary> XmlNameToken = 694 ' XmlNameTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> XmlTextLiteralToken = 695 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> XmlEntityLiteralToken = 696 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> DocumentationCommentLineBreakToken = 697 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents an identifier token. This might include brackets around the name and ''' a type character. ''' </summary> IdentifierToken = 700 ' IdentifierTokenSyntax : SyntaxToken ''' <summary> ''' Represents an integer literal token. ''' </summary> IntegerLiteralToken = 701 ' IntegerLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a floating literal token. ''' </summary> FloatingLiteralToken = 702 ' FloatingLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a Decimal literal token. ''' </summary> DecimalLiteralToken = 703 ' DecimalLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a Date literal token. ''' </summary> DateLiteralToken = 704 ' DateLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a string literal token. ''' </summary> StringLiteralToken = 705 ' StringLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a string literal token. ''' </summary> CharacterLiteralToken = 706 ' CharacterLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents tokens that were skipped by the parser as part of error recovery, ''' and thus are not part of any syntactic structure. ''' </summary> SkippedTokensTrivia = 709 ' SkippedTokensTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents a documentation comment e.g. ''' &lt;Summary&gt; appearing in source. ''' </summary> DocumentationCommentTrivia = 710 ' DocumentationCommentTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' A symbol referenced by a cref attribute (e.g. in a &lt;see&gt; or ''' &lt;seealso&gt; documentation comment tag). For example, the M in &lt;see ''' cref="M" /&gt;. ''' </summary> XmlCrefAttribute = 711 ' XmlCrefAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' A param or type param symbol referenced by a name attribute (e.g. in a ''' &lt;param&gt; or &lt;typeparam&gt; documentation comment tag). For example, the ''' M in &lt;param name="M" /&gt;. ''' </summary> XmlNameAttribute = 712 ' XmlNameAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' ExpressionSyntax node representing the object conditionally accessed. ''' </summary> ConditionalAccessExpression = 713 ' ConditionalAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents true whitespace: spaces, tabs, newlines and the like. ''' </summary> WhitespaceTrivia = 729 ' SyntaxTrivia ''' <summary> ''' Represents line breaks that are syntactically insignificant. ''' </summary> EndOfLineTrivia = 730 ' SyntaxTrivia ''' <summary> ''' Represents colons that are syntactically insignificant. ''' </summary> ColonTrivia = 731 ' SyntaxTrivia ''' <summary> ''' Represents a comment. ''' </summary> CommentTrivia = 732 ' SyntaxTrivia ''' <summary> ''' Represents an explicit line continuation character at the end of a line, i.e., ''' _ ''' </summary> LineContinuationTrivia = 733 ' SyntaxTrivia ''' <summary> ''' Represents a ''' prefix for an XML Documentation Comment. ''' </summary> DocumentationCommentExteriorTrivia = 734 ' SyntaxTrivia ''' <summary> ''' Represents text in a false preprocessor block ''' </summary> DisabledTextTrivia = 735 ' SyntaxTrivia ''' <summary> ''' Represents a #Const pre-processing constant declaration appearing in source. ''' </summary> ConstDirectiveTrivia = 736 ' ConstDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of an #If pre-processing directive appearing in ''' source. ''' </summary> IfDirectiveTrivia = 737 ' IfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of an #If pre-processing directive appearing in ''' source. ''' </summary> ElseIfDirectiveTrivia = 738 ' IfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #Else pre-processing directive appearing in source. ''' </summary> ElseDirectiveTrivia = 739 ' ElseDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End If pre-processing directive appearing in source. ''' </summary> EndIfDirectiveTrivia = 740 ' EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of a #Region directive appearing in source. ''' </summary> RegionDirectiveTrivia = 741 ' RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End Region directive appearing in source. ''' </summary> EndRegionDirectiveTrivia = 744 ' EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of a #ExternalSource pre-processing directive ''' appearing in source. ''' </summary> ExternalSourceDirectiveTrivia = 745 ' ExternalSourceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End ExternalSource pre-processing directive appearing in source. ''' </summary> EndExternalSourceDirectiveTrivia = 746 ' EndExternalSourceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #ExternalChecksum pre-processing directive appearing in source. ''' </summary> ExternalChecksumDirectiveTrivia = 747 ' ExternalChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents #Enable Warning pre-processing directive appearing in source. ''' </summary> EnableWarningDirectiveTrivia = 748 ' EnableWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents #Disable Warning pre-processing directive appearing in source. ''' </summary> DisableWarningDirectiveTrivia = 749 ' DisableWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #r directive appearing in scripts. ''' </summary> ReferenceDirectiveTrivia = 750 ' ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an unrecognized pre-processing directive. This occurs when the ''' parser encounters a hash '#' token at the beginning of a physical line but does ''' recognize the text that follows as a valid Visual Basic pre-processing ''' directive. ''' </summary> BadDirectiveTrivia = 753 ' BadDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an alias identifier followed by an "=" token in an Imports clause. ''' </summary> ImportAliasClause = 754 ' ImportAliasClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents an identifier name followed by a ":=" token in a named argument. ''' </summary> NameColonEquals = 755 ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> SimpleDoLoopBlock = 756 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoWhileLoopBlock = 757 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoUntilLoopBlock = 758 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoLoopWhileBlock = 759 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoLoopUntilBlock = 760 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a simple "Do" statement that begins a "Do ... Loop" block. ''' </summary> SimpleDoStatement = 770 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do While" statement that begins a "Do ... Loop" block. ''' </summary> DoWhileStatement = 771 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do Until" statement that begins a "Do ... Loop" block. ''' </summary> DoUntilStatement = 772 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a simple "Loop" statement that end a "Do ... Loop" block. ''' </summary> SimpleLoopStatement = 773 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Loop While" statement that end a "Do ... Loop" block. ''' </summary> LoopWhileStatement = 774 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Loop Until" statement that end a "Do ... Loop" block. ''' </summary> LoopUntilStatement = 775 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "While ..." clause of a "Do" or "Loop" statement. ''' </summary> WhileClause = 776 ' WhileOrUntilClause : VisualBasicSyntaxNode ''' <summary> ''' Represents an "Until ..." clause of a "Do" or "Loop" statement. ''' </summary> UntilClause = 777 ' WhileOrUntilClause : VisualBasicSyntaxNode ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NameOfKeyword = 778 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a NameOf expression. ''' </summary> NameOfExpression = 779 ' NameOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an interpolated string expression. ''' </summary> InterpolatedStringExpression = 780 ' InterpolatedStringExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents literal text content in an interpolated string. ''' </summary> InterpolatedStringText = 781 ' InterpolatedStringTextSyntax : InterpolatedStringContentSyntax ''' <summary> ''' Represents an embedded expression in an interpolated string expression e.g. '{expression[,alignment][:formatString]}'. ''' </summary> Interpolation = 782 ' InterpolationSyntax : InterpolatedStringContentSyntax ''' <summary> ''' Represents an alignment clause ', alignment' of an interpolated string embedded expression. ''' </summary> InterpolationAlignmentClause = 783 ' InterpolationAlignmentClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a format string clause ':formatString' of an interpolated string embedded expression. ''' </summary> InterpolationFormatClause = 784 ' InterpolationFormatClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a '$"' token in an interpolated string expression. ''' </summary> DollarSignDoubleQuoteToken = 785 ' DollarSignDoubleQuoteTokenSyntax : PunctuationSyntax ''' <summary> ''' Represents literal character data in interpolated string expression. ''' </summary> InterpolatedStringTextToken = 786 ' InterpolatedStringTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents the end of interpolated string when parsing. ''' </summary> EndOfInterpolatedStringToken = 787 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents tuple literal expression. ''' </summary> TupleExpression = 788 ''' <summary> ''' Represents tuple type. ''' </summary> TupleType = 789 ''' <summary> ''' Represents an element of a tuple type supplying only the type ''' </summary> TypedTupleElement = 790 ''' <summary> ''' Represents an element of a tuple type supplying element name and optionally a type. ''' </summary> NamedTupleElement = 791 ''' <summary> ''' Trivia created when merge conflict markers (like "&lt;&lt;&lt;&lt;&lt;&lt;&lt;") are detected in source code ''' </summary> ConflictMarkerTrivia = 792 End Enum End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Enumeration with all Visual Basic syntax node kinds. ''' </summary> Public Enum SyntaxKind As UShort ' ADD NEW SYNTAX TO THE END OF THIS ENUM OR YOU WILL BREAK BINARY COMPATIBILITY None = 0 List = GreenNode.ListKind ''' <summary> ''' A class to represent an empty statement. This can occur when a colon is on a ''' line without anything else. ''' </summary> EmptyStatement = 2 ' EmptyStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndIfStatement = 5 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndUsingStatement = 6 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndWithStatement = 7 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSelectStatement = 8 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndStructureStatement = 9 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndEnumStatement = 10 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndInterfaceStatement = 11 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndClassStatement = 12 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndModuleStatement = 13 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndNamespaceStatement = 14 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSubStatement = 15 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndFunctionStatement = 16 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndGetStatement = 17 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSetStatement = 18 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndPropertyStatement = 19 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndOperatorStatement = 20 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndEventStatement = 21 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndAddHandlerStatement = 22 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndRemoveHandlerStatement = 23 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndRaiseEventStatement = 24 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndWhileStatement = 25 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndTryStatement = 26 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an "End XXX" statement, where XXX is a single keyword. ''' </summary> EndSyncLockStatement = 27 ' EndBlockStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire source file of VB code. ''' </summary> CompilationUnit = 38 ' CompilationUnitSyntax ''' <summary> ''' Represents an Option statement, such as "Option Strict On". ''' </summary> OptionStatement = 41 ' OptionStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Imports statement, which has one or more imports clauses. ''' </summary> ImportsStatement = 42 ' ImportsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ' AliasImportsClause = 43 ' Removed. ''' <summary> ''' Represents the clause of an Imports statement that imports all members of a type or namespace or aliases a type or namespace. ''' </summary> SimpleImportsClause = 44 ' SimpleImportsClauseSyntax : ImportsClauseSyntax ''' <summary> ''' Defines a XML namespace for XML expressions. ''' </summary> XmlNamespaceImportsClause = 45 ' XmlNamespaceImportsClauseSyntax : ImportsClauseSyntax ''' <summary> ''' Represents a Namespace statement, its contents and the End Namespace statement. ''' </summary> NamespaceBlock = 48 ' NamespaceBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a namespace declaration. This node always ''' appears as the Begin of a BlockStatement with Kind=NamespaceBlock. ''' </summary> NamespaceStatement = 49 ' NamespaceStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of Module, its contents and the End statement that ''' ends it. ''' </summary> ModuleBlock = 50 ' ModuleBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Structure, its contents and the End statement ''' that ends it. ''' </summary> StructureBlock = 51 ' StructureBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Interface, its contents and the End statement ''' that ends it. ''' </summary> InterfaceBlock = 52 ' InterfaceBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of a Class its contents and the End statement that ''' ends it. ''' </summary> ClassBlock = 53 ' ClassBlockSyntax : TypeBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a declaration of an Enum, its contents and the End Enum statement ''' that ends it. ''' </summary> EnumBlock = 54 ' EnumBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Inherits statement in a Class, Structure or Interface. ''' </summary> InheritsStatement = 57 ' InheritsStatementSyntax : InheritsOrImplementsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Implements statement in a Class or Structure. ''' </summary> ImplementsStatement = 58 ' ImplementsStatementSyntax : InheritsOrImplementsStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Module declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=ModuleDeclarationBlock. ''' </summary> ModuleStatement = 59 ' ModuleStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Structure declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=StructureDeclarationBlock. ''' </summary> StructureStatement = 60 ' StructureStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Interface declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=InterfaceDeclarationBlock. ''' </summary> InterfaceStatement = 61 ' InterfaceStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of a Class declaration. This node always ''' appears as the Begin of a TypeBlock with Kind=ClassDeclarationBlock. ''' </summary> ClassStatement = 62 ' ClassStatementSyntax : TypeStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the beginning statement of an Enum declaration. This node always ''' appears as the Begin of an EnumBlock with Kind=EnumDeclarationBlock. ''' </summary> EnumStatement = 63 ' EnumStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the type parameter list in a declaration. ''' </summary> TypeParameterList = 66 ' TypeParameterListSyntax ''' <summary> ''' Represents a type parameter on a generic type declaration. ''' </summary> TypeParameter = 67 ' TypeParameterSyntax ''' <summary> ''' One of the type parameter constraints clauses. This represents a constraint ''' clause in the form of "As Constraint". ''' </summary> TypeParameterSingleConstraintClause = 70 ' TypeParameterSingleConstraintClauseSyntax : TypeParameterConstraintClauseSyntax ''' <summary> ''' One of the type parameter constraints clauses. This represents a constraint ''' clause in the form of "As { Constraints }". ''' </summary> TypeParameterMultipleConstraintClause = 71 ' TypeParameterMultipleConstraintClauseSyntax : TypeParameterConstraintClauseSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> NewConstraint = 72 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> ClassConstraint = 73 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' One of the special type parameter constraints: New, Class or Structure. Which ''' kind of special constraint it is can be obtained from the Kind property and is ''' one of: NewConstraint, ReferenceConstraint or ValueConstraint. ''' </summary> StructureConstraint = 74 ' SpecialConstraintSyntax : ConstraintSyntax ''' <summary> ''' Represents a type parameter constraint that is a type. ''' </summary> TypeConstraint = 75 ' TypeConstraintSyntax : ConstraintSyntax ''' <summary> ''' Represents a name and value in an EnumDeclarationBlock. ''' </summary> EnumMemberDeclaration = 78 ' EnumMemberDeclarationSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Function or Sub block declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> SubBlock = 79 ' MethodBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Function or Sub block declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> FunctionBlock = 80 ' MethodBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a constructor block declaration: A declaration that has a beginning ''' declaration, a body of executable statements and an end statement. ''' </summary> ConstructorBlock = 81 ' ConstructorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an Operator block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' </summary> OperatorBlock = 82 ' OperatorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> GetAccessorBlock = 83 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> SetAccessorBlock = 84 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> AddHandlerAccessorBlock = 85 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> RemoveHandlerAccessorBlock = 86 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents an accessor block member declaration: A declaration that has a ''' beginning declaration, a body of executable statements and an end statement. ''' Examples include property accessors and custom event accessors. ''' </summary> RaiseEventAccessorBlock = 87 ' AccessorBlockSyntax : MethodBlockBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a block property declaration: A declaration that has a beginning ''' declaration, some get or set accessor blocks and an end statement. ''' </summary> PropertyBlock = 88 ' PropertyBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a custom event declaration: A declaration that has a beginning event ''' declaration, some accessor blocks and an end statement. ''' </summary> EventBlock = 89 ' EventBlockSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the parameter list in a method declaration. ''' </summary> ParameterList = 92 ' ParameterListSyntax ''' <summary> ''' The statement that declares a Sub or Function. If this method has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> SubStatement = 93 ' MethodStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' The statement that declares a Sub or Function. If this method has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> FunctionStatement = 94 ' MethodStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a constructor. This statement will be the Begin of a ''' BlockStatement with Kind=MethodDeclarationBlock, and the body of the method ''' will be the Body of that BlockStatement. ''' </summary> SubNewStatement = 95 ' SubNewStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A Declare statement that declares an external DLL method. ''' </summary> DeclareSubStatement = 96 ' DeclareStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A Declare statement that declares an external DLL method. ''' </summary> DeclareFunctionStatement = 97 ' DeclareStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a delegate type. ''' </summary> DelegateSubStatement = 98 ' DelegateStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares a delegate type. ''' </summary> DelegateFunctionStatement = 99 ' DelegateStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares an event. If the event being declared is a custom ''' event, this statement will be the Begin of a PropertyOrEventBlock, and the ''' accessors will be part of the Accessors of that node. ''' </summary> EventStatement = 102 ' EventStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' A statement that declares an operator. If this operator has a body, this ''' statement will be the Begin of a BlockStatement with ''' Kind=MethodDeclarationBlock, and the body of the method will be the Body of ''' that BlockStatement. ''' </summary> OperatorStatement = 103 ' OperatorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Statement that declares a property. If this property has accessors declared, ''' this statement will be the Begin of a BlockNode, and the accessors will be the ''' Body of that node. Auto properties are property declarations without a ''' PropertyBlock. ''' </summary> PropertyStatement = 104 ' PropertyStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> GetAccessorStatement = 105 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> SetAccessorStatement = 106 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> AddHandlerAccessorStatement = 107 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> RemoveHandlerAccessorStatement = 108 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Get or Set accessor on a property declaration or an AddHandler, ''' RemoveHandler or RaiseEvent accessor on a custom event declaration. The Kind of ''' the node determines what kind of accessor this is. This statement is always the ''' Begin of a BlockNode, and the body of the accessor is the Body of that node. ''' </summary> RaiseEventAccessorStatement = 111 ' AccessorStatementSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the "Implements ..." clause on a type member, which describes which ''' interface members this member implements. ''' </summary> ImplementsClause = 112 ' ImplementsClauseSyntax ''' <summary> ''' Represents the "Handles ..." clause on a method declaration that describes ''' which events this method handles. ''' </summary> HandlesClause = 113 ' HandlesClauseSyntax ''' <summary> ''' Represents event container specified through special keywords "Me", "MyBase" or ''' "MyClass".. ''' </summary> KeywordEventContainer = 114 ' KeywordEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents event container that refers to a WithEvents member. ''' </summary> WithEventsEventContainer = 115 ' WithEventsEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents event container that refers to a WithEvents member's property. ''' </summary> WithEventsPropertyEventContainer = 116 ' WithEventsPropertyEventContainerSyntax : EventContainerSyntax : ExpressionSyntax ''' <summary> ''' Represents a single handled event in a "Handles ..." clause. ''' </summary> HandlesClauseItem = 117 ' HandlesClauseItemSyntax ''' <summary> ''' Represents the beginning of a declaration. However, not enough syntax is ''' detected to classify this as a field, method, property or event. This is node ''' always represents a syntax error. ''' </summary> IncompleteMember = 118 ' IncompleteMemberSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the declaration of one or more variables or constants, either as ''' local variables or as class/structure members. In the case of a constant, it is ''' represented by having "Const" in the Modifiers (although technically "Const" is ''' not a modifier, it is represented as one in the parse trees.) ''' </summary> FieldDeclaration = 119 ' FieldDeclarationSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the part of a variable or constant declaration statement that ''' associated one or more variable names with a type. ''' </summary> VariableDeclarator = 122 ' VariableDeclaratorSyntax ''' <summary> ''' Represents an "As {type-name}" clause that does not have an initializer or ''' "New". The type has optional attributes associated with it, although attributes ''' are not permitted in all possible places where this node occurs. ''' </summary> SimpleAsClause = 123 ' SimpleAsClauseSyntax : AsClauseSyntax ''' <summary> ''' Represents an "As New {type-name} [arguments] [initializers]" clause in a ''' declaration. The type has optional attributes associated with it, although ''' attributes are not permitted in many places where this node occurs (they are ''' permitted, for example, on automatically implemented properties.) ''' </summary> AsNewClause = 124 ' AsNewClauseSyntax : AsClauseSyntax ''' <summary> ''' Represents a "With {...} clause used to initialize a new object's members. ''' </summary> ObjectMemberInitializer = 125 ' ObjectMemberInitializerSyntax : ObjectCreationInitializerSyntax ''' <summary> ''' Represents a "From {...} clause used to initialize a new collection object's ''' elements. ''' </summary> ObjectCollectionInitializer = 126 ' ObjectCollectionInitializerSyntax : ObjectCreationInitializerSyntax ''' <summary> ''' Represent a field initializer in a With {...} initializer where the field name ''' is inferred from the initializer expression. ''' </summary> InferredFieldInitializer = 127 ' InferredFieldInitializerSyntax : FieldInitializerSyntax ''' <summary> ''' Represent a named field initializer in a With {...} initializer, such as ".x = ''' expr". ''' </summary> NamedFieldInitializer = 128 ' NamedFieldInitializerSyntax : FieldInitializerSyntax ''' <summary> ''' Represents an "= initializer" clause in a declaration for a variable, ''' parameter or automatic property. ''' </summary> EqualsValue = 129 ' EqualsValueSyntax ''' <summary> ''' Represent a parameter to a method, property, constructor, etc. ''' </summary> Parameter = 132 ' ParameterSyntax ''' <summary> ''' Represents an identifier with optional "?" or "()" or "(,,,)" modifiers, as ''' used in parameter declarations and variable declarations. ''' </summary> ModifiedIdentifier = 133 ' ModifiedIdentifierSyntax ''' <summary> ''' Represents a modifier that describes an array type, without bounds, such as ''' "()" or "(,)". ''' </summary> ArrayRankSpecifier = 134 ' ArrayRankSpecifierSyntax ''' <summary> ''' Represents a group of attributes within "&lt;" and "&gt;" brackets. ''' </summary> AttributeList = 135 ' AttributeListSyntax ''' <summary> ''' Represents a single attribute declaration within an attribute list. ''' </summary> Attribute = 136 ' AttributeSyntax ''' <summary> ''' Represents a single attribute declaration within an attribute list. ''' </summary> AttributeTarget = 137 ' AttributeTargetSyntax ''' <summary> ''' Represents a file-level attribute, in which the attributes have no other ''' syntactic element they are attached to. ''' </summary> AttributesStatement = 138 ' AttributesStatementSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represent an expression in a statement context. This may only be a invocation ''' or await expression in standard code but may be any expression in VB ''' Interactive code. ''' </summary> ExpressionStatement = 139 ' ExpressionStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a "? expression" "Print" statement in VB Interactive code. ''' </summary> PrintStatement = 140 ' PrintStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a While...End While statement, including the While, body and End ''' While. ''' </summary> WhileBlock = 141 ' WhileBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire Using...End Using statement, including the Using, body and ''' End Using statements. ''' </summary> UsingBlock = 144 ' UsingBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a entire SyncLock...End SyncLock block, including the SyncLock ''' statement, the enclosed statements, and the End SyncLock statement. ''' </summary> SyncLockBlock = 145 ' SyncLockBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a With...End With block, include the With statement, the body of the ''' block and the End With statement. ''' </summary> WithBlock = 146 ' WithBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents the declaration of one or more local variables or constants. ''' </summary> LocalDeclarationStatement = 147 ' LocalDeclarationStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a label statement. ''' </summary> LabelStatement = 148 ' LabelStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "GoTo" statement. ''' </summary> GoToStatement = 149 ' GoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> IdentifierLabel = 150 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> NumericLabel = 151 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' A label for a GoTo, Resume, or On Error statement. An identifier, line number, ''' or next keyword. ''' </summary> NextLabel = 152 ' LabelSyntax : ExpressionSyntax ''' <summary> ''' Represents a "Stop" or "End" statement. The Kind can be used to determine which ''' kind of statement this is. ''' </summary> StopStatement = 153 ' StopOrEndStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Stop" or "End" statement. The Kind can be used to determine which ''' kind of statement this is. ''' </summary> EndStatement = 156 ' StopOrEndStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitDoStatement = 157 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitForStatement = 158 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitSubStatement = 159 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitFunctionStatement = 160 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitOperatorStatement = 161 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitPropertyStatement = 162 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitTryStatement = 163 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitSelectStatement = 164 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' An exit statement. The kind of block being exited can be found by examining the ''' Kind. ''' </summary> ExitWhileStatement = 165 ' ExitStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueWhileStatement = 166 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueDoStatement = 167 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Continue (block)" statement. THe kind of block referenced can be ''' determined by examining the Kind. ''' </summary> ContinueForStatement = 168 ' ContinueStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Return" statement. ''' </summary> ReturnStatement = 169 ' ReturnStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a line If-Then-Else statement. ''' </summary> SingleLineIfStatement = 170 ' SingleLineIfStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents part of a single line If statement, consisting of a beginning ''' if-statement, followed by a body of statement controlled by that beginning ''' statement. The Kind property returns if this is a SingleLineIf. ''' </summary> SingleLineIfPart = 171 ' SingleLineIfPartSyntax ''' <summary> ''' Represents the Else part of an If statement, consisting of a Else statement, ''' followed by a body of statement controlled by that Else. ''' </summary> SingleLineElseClause = 172 ' SingleLineElseClauseSyntax ''' <summary> ''' Represents a block If...Then...Else...EndIf Statement. The Kind property can be ''' used to determine if it is a block or line If. ''' </summary> MultiLineIfBlock = 173 ' MultiLineIfBlockSyntax : ExecutableStatementSyntax : StatementSyntax ' IfPart = 179 ' This node was removed. ''' <summary> ''' Represents part of an If statement, consisting of a beginning statement (If or ''' ElseIf), followed by a body of statement controlled by that beginning ''' statement. The Kind property returns if this is an If or ElseIf. ''' </summary> ElseIfBlock = 180 ' ElseIfBlockSyntax ''' <summary> ''' Represents the Else part of an If statement, consisting of a Else statement, ''' followed by a body of statement controlled by that Else. ''' </summary> ElseBlock = 181 ' ElseBlockSyntax ''' <summary> ''' Represents the If part or ElseIf part of a If...End If block (or line If). This ''' statement is always the Begin of a IfPart. The Kind can be examined to ''' determine if this is an If or an ElseIf statement. ''' </summary> IfStatement = 182 ' IfStatementSyntax : StatementSyntax ''' <summary> ''' Represents the If part or ElseIf part of a If...End If block (or line If). This ''' statement is always the Begin of a IfPart. The Kind can be examined to ''' determine if this is an If or an ElseIf statement. ''' </summary> ElseIfStatement = 183 ' IfStatementSyntax : StatementSyntax ''' <summary> ''' Represents the Else part of a If...End If block (or line If). This statement is ''' always the Begin of a ElsePart. ''' </summary> ElseStatement = 184 ' ElseStatementSyntax : StatementSyntax ''' <summary> ''' Represents an entire Try...Catch...Finally...End Try statement. ''' </summary> TryBlock = 185 ' TryBlockSyntax : ExecutableStatementSyntax : StatementSyntax ' TryPart = 186 ' This node was removed. ''' <summary> ''' Represents a Catch part of a Try...Catch...Finally...End Try statement, ''' consisting of a Catch statement, followed by a body of statements controlled by ''' that Catch statement. The Kind property returns which kind of part this is. ''' </summary> CatchBlock = 187 ' CatchBlockSyntax ''' <summary> ''' Represents the Finally part of a Try...Catch...Finally...End Try statement, ''' consisting of a Finally statement, followed by a body of statements controlled ''' by the Finally. ''' </summary> FinallyBlock = 188 ' FinallyBlockSyntax ''' <summary> ''' Represents the Try part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a TryPart. ''' </summary> TryStatement = 189 ' TryStatementSyntax : StatementSyntax ''' <summary> ''' Represents the Catch part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a CatchPart. ''' </summary> CatchStatement = 190 ' CatchStatementSyntax : StatementSyntax ''' <summary> ''' Represents the When/Filter clause of a Catch statement ''' </summary> CatchFilterClause = 191 ' CatchFilterClauseSyntax ''' <summary> ''' Represents the Finally part of a Try...Catch...Finally...End Try. This ''' statement is always the Begin of a FinallyPart. ''' </summary> FinallyStatement = 194 ' FinallyStatementSyntax : StatementSyntax ''' <summary> ''' Represents the "Error" statement. ''' </summary> ErrorStatement = 195 ' ErrorStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToZeroStatement = 196 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToMinusOneStatement = 197 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Goto statement. ''' </summary> OnErrorGoToLabelStatement = 198 ' OnErrorGoToStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an OnError Resume Next statement. ''' </summary> OnErrorResumeNextStatement = 199 ' OnErrorResumeNextStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeStatement = 200 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeLabelStatement = 201 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "Resume" statement. The Kind property can be used to determine if ''' this is a "Resume", "Resume Next" or "Resume label" statement. ''' </summary> ResumeNextStatement = 202 ' ResumeStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Select Case block, including the Select Case that begins it, the ''' contains Case blocks and the End Select. ''' </summary> SelectBlock = 203 ' SelectBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Select Case statement. This statement always occurs as the Begin ''' of a SelectBlock. ''' </summary> SelectStatement = 204 ' SelectStatementSyntax : StatementSyntax ''' <summary> ''' Represents a case statement and its subsequent block. ''' </summary> CaseBlock = 207 ' CaseBlockSyntax ''' <summary> ''' Represents a case statement and its subsequent block. ''' </summary> CaseElseBlock = 210 ' CaseBlockSyntax ''' <summary> ''' Represents a Case or Case Else statement. This statement is always the Begin of ''' a CaseBlock. If this is a Case Else statement, the Kind=CaseElse, otherwise the ''' Kind=Case. ''' </summary> CaseStatement = 211 ' CaseStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Case or Case Else statement. This statement is always the Begin of ''' a CaseBlock. If this is a Case Else statement, the Kind=CaseElse, otherwise the ''' Kind=Case. ''' </summary> CaseElseStatement = 212 ' CaseStatementSyntax : StatementSyntax ''' <summary> ''' The "Else" part in a Case Else statement. ''' </summary> ElseCaseClause = 213 ' ElseCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a single value in a Case. ''' </summary> SimpleCaseClause = 214 ' SimpleCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a range "expression To expression" in a Case. ''' </summary> RangeCaseClause = 215 ' RangeCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseEqualsClause = 216 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseNotEqualsClause = 217 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseLessThanClause = 218 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseLessThanOrEqualClause = 219 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseGreaterThanOrEqualClause = 222 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents a relation clause in a Case statement, such as "Is &gt; expression". ''' </summary> CaseGreaterThanClause = 223 ' RelationalCaseClauseSyntax : CaseClauseSyntax ''' <summary> ''' Represents the "SyncLock" statement. This statement always occurs as the Begin ''' of a SyncLockBlock. ''' </summary> SyncLockStatement = 226 ' SyncLockStatementSyntax : StatementSyntax 'DoLoopTopTestBlock = 227 'Removed 'DoLoopBottomTestBlock = 228 'Removed 'DoLoopForeverBlock = 229 'Removed 'DoStatement = 230 'Removed 'LoopStatement = 231 'Removed 'WhileClause = 232 'Removed 'UntilClause = 233 'Removed WhileStatement = 234 ' WhileStatementSyntax : StatementSyntax ''' <summary> ''' Represents a For or For Each block, including the introducing statement, the ''' body and the "Next" (which can be omitted if a containing For has a Next with ''' multiple variables). ''' </summary> ForBlock = 237 ' ForBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a For or For Each block, including the introducing statement, the ''' body and the "Next" (which can be omitted if a containing For has a Next with ''' multiple variables). ''' </summary> ForEachBlock = 238 ' ForBlockSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' The For statement that begins a For-Next block. This statement always occurs as ''' the Begin of a ForBlock. Most of the time, the End of that ForBlock is the ''' corresponding Next statement. However, multiple nested For statements are ended ''' by a single Next statement with multiple variables, then the inner For ''' statements will have End set to Nothing, and the Next statement is the End of ''' the outermost For statement that is being ended. ''' </summary> ForStatement = 239 ' ForStatementSyntax : StatementSyntax ''' <summary> ''' The Step clause in a For Statement. ''' </summary> ForStepClause = 240 ' ForStepClauseSyntax ''' <summary> ''' The For Each statement that begins a For Each-Next block. This statement always ''' occurs as the Begin of a ForBlock, and the body of the For Each-Next is the ''' Body of that ForBlock. Most of the time, the End of that ForBlock is the ''' corresponding Next statement. However, multiple nested For statements are ended ''' by a single Next statement with multiple variables, then the inner For ''' statements will have End set to Nothing, and the Next statement is the End of ''' the outermost For statement that is being ended. ''' </summary> ForEachStatement = 241 ' ForEachStatementSyntax : StatementSyntax ''' <summary> ''' The Next statement that ends a For-Next or For Each-Next block. This statement ''' always occurs as the End of a ForBlock (with Kind=ForBlock or ForEachBlock), ''' and the body of the For-Next is the Body of that ForBlock. The Begin of that ''' ForBlock has the corresponding For or For Each statement. ''' </summary> NextStatement = 242 ' NextStatementSyntax : StatementSyntax ''' <summary> ''' The Using statement that begins a Using block. This statement always occurs as ''' the Begin of a UsingBlock, and the body of the Using is the Body of that ''' UsingBlock. ''' </summary> UsingStatement = 243 ' UsingStatementSyntax : StatementSyntax ''' <summary> ''' Represents a Throw statement. ''' </summary> ThrowStatement = 246 ' ThrowStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> SimpleAssignmentStatement = 247 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> MidAssignmentStatement = 248 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> AddAssignmentStatement = 249 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> SubtractAssignmentStatement = 250 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> MultiplyAssignmentStatement = 251 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> DivideAssignmentStatement = 252 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> IntegerDivideAssignmentStatement = 253 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> ExponentiateAssignmentStatement = 254 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> LeftShiftAssignmentStatement = 255 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> RightShiftAssignmentStatement = 258 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a simple, compound, or Mid assignment statement. Which one can be ''' determined by checking the Kind. ''' </summary> ConcatenateAssignmentStatement = 259 ' AssignmentStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a left-hand side of a MidAssignment statement. ''' </summary> MidExpression = 260 ' MidExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represent a call statement (also known as a invocation statement). ''' </summary> CallStatement = 261 ' CallStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an AddHandler or RemoveHandler statement. The Kind property ''' determines which one. ''' </summary> AddHandlerStatement = 262 ' AddRemoveHandlerStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents an AddHandler or RemoveHandler statement. The Kind property ''' determines which one. ''' </summary> RemoveHandlerStatement = 263 ' AddRemoveHandlerStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a RaiseEvent statement. ''' </summary> RaiseEventStatement = 264 ' RaiseEventStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a "With" statement. This statement always occurs as the ''' BeginStatement of a WithBlock, and the body of the With is the Body of that ''' WithBlock. ''' </summary> WithStatement = 265 ' WithStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement. ''' </summary> ReDimStatement = 266 ' ReDimStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement. ''' </summary> ReDimPreserveStatement = 267 ' ReDimStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a ReDim statement clause. ''' </summary> RedimClause = 270 ' RedimClauseSyntax ''' <summary> ''' Represents an "Erase" statement. ''' </summary> EraseStatement = 271 ' EraseStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> CharacterLiteralExpression = 272 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> TrueLiteralExpression = 273 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> FalseLiteralExpression = 274 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> NumericLiteralExpression = 275 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> DateLiteralExpression = 276 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> StringLiteralExpression = 279 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a literal. The kind of literal is determined by the Kind property: ''' IntegerLiteral, CharacterLiteral, BooleanLiteral, DecimalLiteral, ''' FloatingLiteral, DateLiteral or StringLiteral. The value of the literal can be ''' determined by casting the associated Token to the correct type and getting the ''' value from the token. ''' </summary> NothingLiteralExpression = 280 ' LiteralExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a parenthesized expression. ''' </summary> ParenthesizedExpression = 281 ' ParenthesizedExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "Me" ''' </summary> MeExpression = 282 ' MeExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "MyBase" ''' </summary> MyBaseExpression = 283 ' MyBaseExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Identifies the special instance "MyClass" ''' </summary> MyClassExpression = 284 ' MyClassExpressionSyntax : InstanceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a GetType expression. ''' </summary> GetTypeExpression = 285 ' GetTypeExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a TypeOf...Is or IsNot expression. ''' </summary> TypeOfIsExpression = 286 ' TypeOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a TypeOf...Is or IsNot expression. ''' </summary> TypeOfIsNotExpression = 287 ' TypeOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a GetXmlNamespace expression. ''' </summary> GetXmlNamespaceExpression = 290 ' GetXmlNamespaceExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents member access (.name) or dictionary access (!name). The Kind ''' property determines which kind of access. ''' </summary> SimpleMemberAccessExpression = 291 ' MemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents member access (.name) or dictionary access (!name). The Kind ''' property determines which kind of access. ''' </summary> DictionaryAccessExpression = 292 ' MemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlElementAccessExpression = 293 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlDescendantAccessExpression = 294 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML member element access (node.&lt;Element&gt;), attribute ''' access (node.@Attribute) or descendants access (node...&lt;Descendant&gt;). The ''' Kind property determines which kind of access. ''' </summary> XmlAttributeAccessExpression = 295 ' XmlMemberAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an invocation expression consisting of an invocation target and an ''' optional argument list or an array, parameterized property or object default ''' property index. ''' </summary> InvocationExpression = 296 ' InvocationExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a New expression that creates a new non-array object, possibly with ''' a "With" or "From" clause. ''' </summary> ObjectCreationExpression = 297 ' ObjectCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a New expression that create an object of anonymous type. ''' </summary> AnonymousObjectCreationExpression = 298 ' AnonymousObjectCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an expression that creates a new array. ''' </summary> ArrayCreationExpression = 301 ' ArrayCreationExpressionSyntax : NewExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an expression that creates a new array without naming the element ''' type. ''' </summary> CollectionInitializer = 302 ' CollectionInitializerSyntax : ExpressionSyntax CTypeExpression = 303 ' CTypeExpressionSyntax : CastExpressionSyntax : ExpressionSyntax DirectCastExpression = 304 ' DirectCastExpressionSyntax : CastExpressionSyntax : ExpressionSyntax TryCastExpression = 305 ' TryCastExpressionSyntax : CastExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a cast to a pre-defined type using a pre-defined cast expression, ''' such as CInt or CLng. ''' </summary> PredefinedCastExpression = 306 ' PredefinedCastExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AddExpression = 307 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> SubtractExpression = 308 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> MultiplyExpression = 309 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> DivideExpression = 310 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IntegerDivideExpression = 311 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ExponentiateExpression = 314 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LeftShiftExpression = 315 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> RightShiftExpression = 316 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ConcatenateExpression = 317 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ModuloExpression = 318 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> EqualsExpression = 319 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> NotEqualsExpression = 320 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LessThanExpression = 321 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LessThanOrEqualExpression = 322 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> GreaterThanOrEqualExpression = 323 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> GreaterThanExpression = 324 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IsExpression = 325 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> IsNotExpression = 326 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> LikeExpression = 327 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> OrExpression = 328 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> ExclusiveOrExpression = 329 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AndExpression = 330 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> OrElseExpression = 331 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a binary operator. The Kind property classifies the operators into ''' similar kind of operators (arithmetic, relational, logical or string); the ''' exact operation being performed is determined by the Operator property. ''' </summary> AndAlsoExpression = 332 ' BinaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> UnaryPlusExpression = 333 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> UnaryMinusExpression = 334 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> NotExpression = 335 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a unary operator: Plus, Negate, Not or AddressOf. ''' </summary> AddressOfExpression = 336 ' UnaryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a conditional expression, If(condition, true-expr, false-expr) or ''' If(expr, nothing-expr). ''' </summary> BinaryConditionalExpression = 337 ' BinaryConditionalExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a conditional expression, If(condition, true-expr, false-expr) or ''' If(expr, nothing-expr). ''' </summary> TernaryConditionalExpression = 338 ' TernaryConditionalExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single line lambda expression. ''' </summary> SingleLineFunctionLambdaExpression = 339 ' SingleLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single line lambda expression. ''' </summary> SingleLineSubLambdaExpression = 342 ' SingleLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a multi-line lambda expression. ''' </summary> MultiLineFunctionLambdaExpression = 343 ' MultiLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a multi-line lambda expression. ''' </summary> MultiLineSubLambdaExpression = 344 ' MultiLineLambdaExpressionSyntax : LambdaExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents the header part of a lambda expression ''' </summary> SubLambdaHeader = 345 ' LambdaHeaderSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents the header part of a lambda expression ''' </summary> FunctionLambdaHeader = 346 ' LambdaHeaderSyntax : MethodBaseSyntax : DeclarationStatementSyntax : StatementSyntax ''' <summary> ''' Represents a parenthesized argument list. ''' </summary> ArgumentList = 347 ' ArgumentListSyntax ''' <summary> ''' Represents an omitted argument in an argument list. An omitted argument is not ''' considered a syntax error but a valid case when no argument is required. ''' </summary> OmittedArgument = 348 ' OmittedArgumentSyntax : ArgumentSyntax ''' <summary> ''' Represents an argument that is just an optional argument name and an expression. ''' </summary> SimpleArgument = 349 ' SimpleArgumentSyntax : ArgumentSyntax ' NamedArgument = 350 ' Removed ''' <summary> ''' Represents a range argument, such as "0 to 5", used in array bounds. The ''' "Value" property represents the upper bound of the range. ''' </summary> RangeArgument = 351 ' RangeArgumentSyntax : ArgumentSyntax ''' <summary> ''' This class represents a query expression. A query expression is composed of one ''' or more query operators in a row. The first query operator must be a From or ''' Aggregate. ''' </summary> QueryExpression = 352 ' QueryExpressionSyntax : ExpressionSyntax ''' <summary> ''' Describes a single variable of the form "x [As Type] In expression" for use in ''' query expressions. ''' </summary> CollectionRangeVariable = 353 ' CollectionRangeVariableSyntax ''' <summary> ''' Describes a single variable of the form "[x [As Type] =] expression" for use in ''' query expressions. ''' </summary> ExpressionRangeVariable = 354 ' ExpressionRangeVariableSyntax ''' <summary> ''' Describes a single variable of the form "[x [As Type] =] aggregation-function" ''' for use in the Into clause of Aggregate or Group By or Group Join query ''' operators. ''' </summary> AggregationRangeVariable = 355 ' AggregationRangeVariableSyntax ''' <summary> ''' Represents the name and optional type of an expression range variable. ''' </summary> VariableNameEquals = 356 ' VariableNameEqualsSyntax ''' <summary> ''' Represents an invocation of an Aggregation function in the aggregation range ''' variable declaration of a Group By, Group Join or Aggregate query operator. ''' </summary> FunctionAggregation = 357 ' FunctionAggregationSyntax : AggregationSyntax : ExpressionSyntax ''' <summary> ''' Represents the use of "Group" as the aggregation function in the in the ''' aggregation range variable declaration of a Group By or Group Join query ''' operator. ''' </summary> GroupAggregation = 358 ' GroupAggregationSyntax : AggregationSyntax : ExpressionSyntax ''' <summary> ''' Represents a "From" query operator. If this is the beginning of a query, the ''' Source will be Nothing. Otherwise, the Source will be the part of the query to ''' the left of the From. ''' </summary> FromClause = 359 ' FromClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Let" query operator. ''' </summary> LetClause = 360 ' LetClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents an Aggregate query operator. ''' </summary> AggregateClause = 361 ' AggregateClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Distinct" query operator. ''' </summary> DistinctClause = 362 ' DistinctClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Where" query operator. ''' </summary> WhereClause = 363 ' WhereClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip While" or "Take While" query operator. The Kind property ''' tells which. ''' </summary> SkipWhileClause = 364 ' PartitionWhileClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip While" or "Take While" query operator. The Kind property ''' tells which. ''' </summary> TakeWhileClause = 365 ' PartitionWhileClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip" or "Take" query operator. The Kind property tells which. ''' </summary> SkipClause = 366 ' PartitionClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents a "Skip" or "Take" query operator. The Kind property tells which. ''' </summary> TakeClause = 367 ' PartitionClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Group By" query operator. ''' </summary> GroupByClause = 368 ' GroupByClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "expression Equals expression" condition in a Join. ''' </summary> JoinCondition = 369 ' JoinConditionSyntax ''' <summary> ''' Represents a Join query operator. ''' </summary> SimpleJoinClause = 370 ' SimpleJoinClauseSyntax : JoinClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Group Join" query operator. ''' </summary> GroupJoinClause = 371 ' GroupJoinClauseSyntax : JoinClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents the "Order By" query operator. ''' </summary> OrderByClause = 372 ' OrderByClauseSyntax : QueryClauseSyntax ''' <summary> ''' An expression to order by, plus an optional ordering. The Kind indicates ''' whether to order in ascending or descending order. ''' </summary> AscendingOrdering = 375 ' OrderingSyntax ''' <summary> ''' An expression to order by, plus an optional ordering. The Kind indicates ''' whether to order in ascending or descending order. ''' </summary> DescendingOrdering = 376 ' OrderingSyntax ''' <summary> ''' Represents the "Select" query operator. ''' </summary> SelectClause = 377 ' SelectClauseSyntax : QueryClauseSyntax ''' <summary> ''' Represents an XML Document literal expression. ''' </summary> XmlDocument = 378 ' XmlDocumentSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the XML declaration prologue in an XML literal expression. ''' </summary> XmlDeclaration = 379 ' XmlDeclarationSyntax ''' <summary> ''' Represents an XML document prologue option - version, encoding, standalone or ''' whitespace in an XML literal expression. ''' </summary> XmlDeclarationOption = 380 ' XmlDeclarationOptionSyntax ''' <summary> ''' Represents an XML element with content in an XML literal expression. ''' </summary> XmlElement = 381 ' XmlElementSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents Xml text. ''' </summary> XmlText = 382 ' XmlTextSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the start tag of an XML element of the form &lt;element&gt;. ''' </summary> XmlElementStartTag = 383 ' XmlElementStartTagSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents the end tag of an XML element of the form &lt;/element&gt;. ''' </summary> XmlElementEndTag = 384 ' XmlElementEndTagSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an empty XML element of the form &lt;element /&gt; ''' </summary> XmlEmptyElement = 385 ' XmlEmptyElementSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML attribute in an XML literal expression. ''' </summary> XmlAttribute = 386 ' XmlAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents a string of XML characters embedded as the content of an XML ''' element. ''' </summary> XmlString = 387 ' XmlStringSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form 'name' appearing in GetXmlNamespace(). ''' </summary> XmlPrefixName = 388 ' XmlPrefixNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form 'name' or 'namespace:name' appearing in ''' source as part of an XML literal or member access expression or an XML ''' namespace import clause. ''' </summary> XmlName = 389 ' XmlNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML name of the form &lt;xml-name&gt; appearing in source as part ''' of an XML literal or member access expression or an XML namespace import ''' clause. ''' </summary> XmlBracketedName = 390 ' XmlBracketedNameSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML namespace prefix of the form 'prefix:' as in xml:ns="". ''' </summary> XmlPrefix = 391 ' XmlPrefixSyntax ''' <summary> ''' Represents an XML comment of the form &lt;!-- Comment --&gt; appearing in an ''' XML literal expression. ''' </summary> XmlComment = 392 ' XmlCommentSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML processing instruction of the form '&lt;? XMLProcessingTarget ''' XMLProcessingValue ?&gt;'. ''' </summary> XmlProcessingInstruction = 393 ' XmlProcessingInstructionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an XML CDATA section in an XML literal expression. ''' </summary> XmlCDataSection = 394 ' XmlCDataSectionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an embedded expression in an XML literal e.g. '&lt;name&gt;&lt;%= ''' obj.Name =%&gt;&lt;/name&gt;'. ''' </summary> XmlEmbeddedExpression = 395 ' XmlEmbeddedExpressionSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' Represents an array type, such as "A() or "A(,)", without bounds specified for ''' the array. ''' </summary> ArrayType = 396 ' ArrayTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' A type name that represents a nullable type, such as "Integer?". ''' </summary> NullableType = 397 ' NullableTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents an occurrence of a Visual Basic built-in type such as Integer or ''' String in source code. ''' </summary> PredefinedType = 398 ' PredefinedTypeSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a type name consisting of a single identifier (which might include ''' brackets or a type character). ''' </summary> IdentifierName = 399 ' IdentifierNameSyntax : SimpleNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a simple type name with one or more generic arguments, such as "X(Of ''' Y, Z). ''' </summary> GenericName = 400 ' GenericNameSyntax : SimpleNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a qualified type name, for example X.Y or X(Of Z).Y. ''' </summary> QualifiedName = 401 ' QualifiedNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a name in the global namespace. ''' </summary> GlobalName = 402 ' GlobalNameSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represents a parenthesized list of generic type arguments. ''' </summary> TypeArgumentList = 403 ' TypeArgumentListSyntax ''' <summary> ''' Syntax node class that represents a value of 'cref' attribute inside ''' documentation comment trivia. ''' </summary> CrefReference = 404 ' CrefReferenceSyntax ''' <summary> ''' Represents a parenthesized list of argument types for a signature inside ''' CrefReferenceSyntax syntax. ''' </summary> CrefSignature = 407 ' CrefSignatureSyntax CrefSignaturePart = 408 ' CrefSignaturePartSyntax CrefOperatorReference = 409 ' CrefOperatorReferenceSyntax : NameSyntax : TypeSyntax : ExpressionSyntax QualifiedCrefOperatorReference = 410 ' QualifiedCrefOperatorReferenceSyntax : NameSyntax : TypeSyntax : ExpressionSyntax ''' <summary> ''' Represent a Yield statement. ''' </summary> YieldStatement = 411 ' YieldStatementSyntax : ExecutableStatementSyntax : StatementSyntax ''' <summary> ''' Represent a Await expression. ''' </summary> AwaitExpression = 412 ' AwaitExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AddHandlerKeyword = 413 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AddressOfKeyword = 414 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AliasKeyword = 415 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AndKeyword = 416 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AndAlsoKeyword = 417 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AsKeyword = 418 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> BooleanKeyword = 421 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByRefKeyword = 422 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByteKeyword = 423 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByValKeyword = 424 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CallKeyword = 425 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CaseKeyword = 426 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CatchKeyword = 427 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CBoolKeyword = 428 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CByteKeyword = 429 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CCharKeyword = 432 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDateKeyword = 433 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDecKeyword = 434 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CDblKeyword = 435 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CharKeyword = 436 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CIntKeyword = 437 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ClassKeyword = 438 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CLngKeyword = 439 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CObjKeyword = 440 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ConstKeyword = 441 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReferenceKeyword = 442 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ContinueKeyword = 443 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CSByteKeyword = 444 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CShortKeyword = 445 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CSngKeyword = 446 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CStrKeyword = 447 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CTypeKeyword = 448 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CUIntKeyword = 449 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CULngKeyword = 450 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CUShortKeyword = 453 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DateKeyword = 454 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DecimalKeyword = 455 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DeclareKeyword = 456 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DefaultKeyword = 457 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DelegateKeyword = 458 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DimKeyword = 459 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DirectCastKeyword = 460 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DoKeyword = 461 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DoubleKeyword = 462 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EachKeyword = 463 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ElseKeyword = 464 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ElseIfKeyword = 465 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EndKeyword = 466 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EnumKeyword = 467 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EraseKeyword = 468 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ErrorKeyword = 469 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EventKeyword = 470 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExitKeyword = 471 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FalseKeyword = 474 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FinallyKeyword = 475 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ForKeyword = 476 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FriendKeyword = 477 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FunctionKeyword = 478 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetKeyword = 479 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetTypeKeyword = 480 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GetXmlNamespaceKeyword = 481 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GlobalKeyword = 482 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GoToKeyword = 483 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> HandlesKeyword = 484 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IfKeyword = 485 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ImplementsKeyword = 486 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ImportsKeyword = 487 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InKeyword = 488 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InheritsKeyword = 489 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IntegerKeyword = 490 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InterfaceKeyword = 491 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsKeyword = 492 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsNotKeyword = 495 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LetKeyword = 496 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LibKeyword = 497 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LikeKeyword = 498 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LongKeyword = 499 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> LoopKeyword = 500 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MeKeyword = 501 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ModKeyword = 502 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ModuleKeyword = 503 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MustInheritKeyword = 504 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MustOverrideKeyword = 505 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MyBaseKeyword = 506 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MyClassKeyword = 507 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NamespaceKeyword = 508 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NarrowingKeyword = 509 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NextKeyword = 510 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NewKeyword = 511 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotKeyword = 512 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NothingKeyword = 513 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotInheritableKeyword = 516 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NotOverridableKeyword = 517 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ObjectKeyword = 518 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OfKeyword = 519 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OnKeyword = 520 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OperatorKeyword = 521 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OptionKeyword = 522 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OptionalKeyword = 523 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrKeyword = 524 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrElseKeyword = 525 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverloadsKeyword = 526 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverridableKeyword = 527 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OverridesKeyword = 528 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ParamArrayKeyword = 529 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PartialKeyword = 530 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PrivateKeyword = 531 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PropertyKeyword = 532 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ProtectedKeyword = 533 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PublicKeyword = 534 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RaiseEventKeyword = 537 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReadOnlyKeyword = 538 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReDimKeyword = 539 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> REMKeyword = 540 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RemoveHandlerKeyword = 541 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ResumeKeyword = 542 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ReturnKeyword = 543 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SByteKeyword = 544 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SelectKeyword = 545 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SetKeyword = 546 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ShadowsKeyword = 547 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SharedKeyword = 548 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ShortKeyword = 549 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SingleKeyword = 550 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StaticKeyword = 551 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StepKeyword = 552 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StopKeyword = 553 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StringKeyword = 554 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StructureKeyword = 555 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SubKeyword = 558 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SyncLockKeyword = 559 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ThenKeyword = 560 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ThrowKeyword = 561 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ToKeyword = 562 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TrueKeyword = 563 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TryKeyword = 564 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TryCastKeyword = 565 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TypeOfKeyword = 566 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UIntegerKeyword = 567 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ULongKeyword = 568 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UShortKeyword = 569 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UsingKeyword = 570 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhenKeyword = 571 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhileKeyword = 572 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WideningKeyword = 573 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WithKeyword = 574 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WithEventsKeyword = 575 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WriteOnlyKeyword = 578 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> XorKeyword = 579 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EndIfKeyword = 580 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GosubKeyword = 581 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> VariantKeyword = 582 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WendKeyword = 583 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AggregateKeyword = 584 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AllKeyword = 585 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AnsiKeyword = 586 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AscendingKeyword = 587 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AssemblyKeyword = 588 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AutoKeyword = 589 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> BinaryKeyword = 590 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ByKeyword = 591 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CompareKeyword = 592 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> CustomKeyword = 593 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DescendingKeyword = 594 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DisableKeyword = 595 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> DistinctKeyword = 596 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EnableKeyword = 599 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> EqualsKeyword = 600 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExplicitKeyword = 601 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExternalSourceKeyword = 602 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> ExternalChecksumKeyword = 603 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> FromKeyword = 604 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> GroupKeyword = 605 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> InferKeyword = 606 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IntoKeyword = 607 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsFalseKeyword = 608 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IsTrueKeyword = 609 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> JoinKeyword = 610 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> KeyKeyword = 611 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> MidKeyword = 612 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OffKeyword = 613 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OrderKeyword = 614 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> OutKeyword = 615 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> PreserveKeyword = 616 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> RegionKeyword = 617 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> SkipKeyword = 620 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> StrictKeyword = 621 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TakeKeyword = 622 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TextKeyword = 623 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UnicodeKeyword = 624 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> UntilKeyword = 625 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WarningKeyword = 626 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> WhereKeyword = 627 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> TypeKeyword = 628 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> XmlKeyword = 629 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AsyncKeyword = 630 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> AwaitKeyword = 631 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> IteratorKeyword = 632 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> YieldKeyword = 633 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ExclamationToken = 634 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AtToken = 635 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CommaToken = 636 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> HashToken = 637 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AmpersandToken = 638 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SingleQuoteToken = 641 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> OpenParenToken = 642 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CloseParenToken = 643 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> OpenBraceToken = 644 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CloseBraceToken = 645 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SemicolonToken = 646 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AsteriskToken = 647 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PlusToken = 648 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusToken = 649 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> DotToken = 650 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashToken = 651 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ColonToken = 652 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanToken = 653 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanEqualsToken = 654 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanGreaterThanToken = 655 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EqualsToken = 656 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanToken = 657 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanEqualsToken = 658 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BackslashToken = 659 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CaretToken = 662 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> ColonEqualsToken = 663 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AmpersandEqualsToken = 664 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> AsteriskEqualsToken = 665 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PlusEqualsToken = 666 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusEqualsToken = 667 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashEqualsToken = 668 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BackslashEqualsToken = 669 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> CaretEqualsToken = 670 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanLessThanToken = 671 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanGreaterThanToken = 672 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanLessThanEqualsToken = 673 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> GreaterThanGreaterThanEqualsToken = 674 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> QuestionToken = 675 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> DoubleQuoteToken = 676 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> StatementTerminatorToken = 677 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndOfFileToken = 678 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EmptyToken = 679 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> SlashGreaterThanToken = 680 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanSlashToken = 683 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanExclamationMinusMinusToken = 684 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> MinusMinusGreaterThanToken = 685 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanQuestionToken = 686 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> QuestionGreaterThanToken = 687 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> LessThanPercentEqualsToken = 688 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> PercentGreaterThanToken = 689 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> BeginCDataToken = 690 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndCDataToken = 691 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a single punctuation mark or operator in a VB program. Which one can ''' be determined from the Kind property. ''' </summary> EndOfXmlToken = 692 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents a sequence of characters appearing in source with no possible ''' meaning in the Visual Basic language (e.g. the semicolon ';'). This token ''' should only appear in SkippedTokenTrivia as an artifact of parsing error ''' recovery. ''' </summary> BadToken = 693 ' BadTokenSyntax : PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents an Xml NCName per Namespaces in XML 1.0 ''' </summary> XmlNameToken = 694 ' XmlNameTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> XmlTextLiteralToken = 695 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> XmlEntityLiteralToken = 696 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents character data in Xml content also known as PCData or in an Xml ''' attribute value. All text is here for now even text that does not need ''' normalization such as comment, pi and cdata text. ''' </summary> DocumentationCommentLineBreakToken = 697 ' XmlTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents an identifier token. This might include brackets around the name and ''' a type character. ''' </summary> IdentifierToken = 700 ' IdentifierTokenSyntax : SyntaxToken ''' <summary> ''' Represents an integer literal token. ''' </summary> IntegerLiteralToken = 701 ' IntegerLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a floating literal token. ''' </summary> FloatingLiteralToken = 702 ' FloatingLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a Decimal literal token. ''' </summary> DecimalLiteralToken = 703 ' DecimalLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a Date literal token. ''' </summary> DateLiteralToken = 704 ' DateLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a string literal token. ''' </summary> StringLiteralToken = 705 ' StringLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents a string literal token. ''' </summary> CharacterLiteralToken = 706 ' CharacterLiteralTokenSyntax : SyntaxToken ''' <summary> ''' Represents tokens that were skipped by the parser as part of error recovery, ''' and thus are not part of any syntactic structure. ''' </summary> SkippedTokensTrivia = 709 ' SkippedTokensTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents a documentation comment e.g. ''' &lt;Summary&gt; appearing in source. ''' </summary> DocumentationCommentTrivia = 710 ' DocumentationCommentTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' A symbol referenced by a cref attribute (e.g. in a &lt;see&gt; or ''' &lt;seealso&gt; documentation comment tag). For example, the M in &lt;see ''' cref="M" /&gt;. ''' </summary> XmlCrefAttribute = 711 ' XmlCrefAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' A param or type param symbol referenced by a name attribute (e.g. in a ''' &lt;param&gt; or &lt;typeparam&gt; documentation comment tag). For example, the ''' M in &lt;param name="M" /&gt;. ''' </summary> XmlNameAttribute = 712 ' XmlNameAttributeSyntax : BaseXmlAttributeSyntax : XmlNodeSyntax : ExpressionSyntax ''' <summary> ''' ExpressionSyntax node representing the object conditionally accessed. ''' </summary> ConditionalAccessExpression = 713 ' ConditionalAccessExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents true whitespace: spaces, tabs, newlines and the like. ''' </summary> WhitespaceTrivia = 729 ' SyntaxTrivia ''' <summary> ''' Represents line breaks that are syntactically insignificant. ''' </summary> EndOfLineTrivia = 730 ' SyntaxTrivia ''' <summary> ''' Represents colons that are syntactically insignificant. ''' </summary> ColonTrivia = 731 ' SyntaxTrivia ''' <summary> ''' Represents a comment. ''' </summary> CommentTrivia = 732 ' SyntaxTrivia ''' <summary> ''' Represents an explicit line continuation character at the end of a line, i.e., ''' _ ''' </summary> LineContinuationTrivia = 733 ' SyntaxTrivia ''' <summary> ''' Represents a ''' prefix for an XML Documentation Comment. ''' </summary> DocumentationCommentExteriorTrivia = 734 ' SyntaxTrivia ''' <summary> ''' Represents text in a false preprocessor block ''' </summary> DisabledTextTrivia = 735 ' SyntaxTrivia ''' <summary> ''' Represents a #Const pre-processing constant declaration appearing in source. ''' </summary> ConstDirectiveTrivia = 736 ' ConstDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of an #If pre-processing directive appearing in ''' source. ''' </summary> IfDirectiveTrivia = 737 ' IfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of an #If pre-processing directive appearing in ''' source. ''' </summary> ElseIfDirectiveTrivia = 738 ' IfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #Else pre-processing directive appearing in source. ''' </summary> ElseDirectiveTrivia = 739 ' ElseDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End If pre-processing directive appearing in source. ''' </summary> EndIfDirectiveTrivia = 740 ' EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of a #Region directive appearing in source. ''' </summary> RegionDirectiveTrivia = 741 ' RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End Region directive appearing in source. ''' </summary> EndRegionDirectiveTrivia = 744 ' EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents the beginning of a #ExternalSource pre-processing directive ''' appearing in source. ''' </summary> ExternalSourceDirectiveTrivia = 745 ' ExternalSourceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #End ExternalSource pre-processing directive appearing in source. ''' </summary> EndExternalSourceDirectiveTrivia = 746 ' EndExternalSourceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #ExternalChecksum pre-processing directive appearing in source. ''' </summary> ExternalChecksumDirectiveTrivia = 747 ' ExternalChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents #Enable Warning pre-processing directive appearing in source. ''' </summary> EnableWarningDirectiveTrivia = 748 ' EnableWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents #Disable Warning pre-processing directive appearing in source. ''' </summary> DisableWarningDirectiveTrivia = 749 ' DisableWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an #r directive appearing in scripts. ''' </summary> ReferenceDirectiveTrivia = 750 ' ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an unrecognized pre-processing directive. This occurs when the ''' parser encounters a hash '#' token at the beginning of a physical line but does ''' recognize the text that follows as a valid Visual Basic pre-processing ''' directive. ''' </summary> BadDirectiveTrivia = 753 ' BadDirectiveTriviaSyntax : DirectiveTriviaSyntax : StructuredTriviaSyntax ''' <summary> ''' Represents an alias identifier followed by an "=" token in an Imports clause. ''' </summary> ImportAliasClause = 754 ' ImportAliasClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents an identifier name followed by a ":=" token in a named argument. ''' </summary> NameColonEquals = 755 ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> SimpleDoLoopBlock = 756 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoWhileLoopBlock = 757 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoUntilLoopBlock = 758 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoLoopWhileBlock = 759 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do ... Loop" block. ''' </summary> DoLoopUntilBlock = 760 ' DoLoopBlockSyntax : ExecutableStatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a simple "Do" statement that begins a "Do ... Loop" block. ''' </summary> SimpleDoStatement = 770 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do While" statement that begins a "Do ... Loop" block. ''' </summary> DoWhileStatement = 771 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Do Until" statement that begins a "Do ... Loop" block. ''' </summary> DoUntilStatement = 772 ' DoStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a simple "Loop" statement that end a "Do ... Loop" block. ''' </summary> SimpleLoopStatement = 773 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Loop While" statement that end a "Do ... Loop" block. ''' </summary> LoopWhileStatement = 774 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "Loop Until" statement that end a "Do ... Loop" block. ''' </summary> LoopUntilStatement = 775 ' LoopStatement : StatementSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a "While ..." clause of a "Do" or "Loop" statement. ''' </summary> WhileClause = 776 ' WhileOrUntilClause : VisualBasicSyntaxNode ''' <summary> ''' Represents an "Until ..." clause of a "Do" or "Loop" statement. ''' </summary> UntilClause = 777 ' WhileOrUntilClause : VisualBasicSyntaxNode ''' <summary> ''' Represents a single keyword in a VB program. Which keyword can be determined ''' from the Kind property. ''' </summary> NameOfKeyword = 778 ' KeywordSyntax : SyntaxToken ''' <summary> ''' Represents a NameOf expression. ''' </summary> NameOfExpression = 779 ' NameOfExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents an interpolated string expression. ''' </summary> InterpolatedStringExpression = 780 ' InterpolatedStringExpressionSyntax : ExpressionSyntax ''' <summary> ''' Represents literal text content in an interpolated string. ''' </summary> InterpolatedStringText = 781 ' InterpolatedStringTextSyntax : InterpolatedStringContentSyntax ''' <summary> ''' Represents an embedded expression in an interpolated string expression e.g. '{expression[,alignment][:formatString]}'. ''' </summary> Interpolation = 782 ' InterpolationSyntax : InterpolatedStringContentSyntax ''' <summary> ''' Represents an alignment clause ', alignment' of an interpolated string embedded expression. ''' </summary> InterpolationAlignmentClause = 783 ' InterpolationAlignmentClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a format string clause ':formatString' of an interpolated string embedded expression. ''' </summary> InterpolationFormatClause = 784 ' InterpolationFormatClauseSyntax : VisualBasicSyntaxNode ''' <summary> ''' Represents a '$"' token in an interpolated string expression. ''' </summary> DollarSignDoubleQuoteToken = 785 ' DollarSignDoubleQuoteTokenSyntax : PunctuationSyntax ''' <summary> ''' Represents literal character data in interpolated string expression. ''' </summary> InterpolatedStringTextToken = 786 ' InterpolatedStringTextTokenSyntax : SyntaxToken ''' <summary> ''' Represents the end of interpolated string when parsing. ''' </summary> EndOfInterpolatedStringToken = 787 ' PunctuationSyntax : SyntaxToken ''' <summary> ''' Represents tuple literal expression. ''' </summary> TupleExpression = 788 ''' <summary> ''' Represents tuple type. ''' </summary> TupleType = 789 ''' <summary> ''' Represents an element of a tuple type supplying only the type ''' </summary> TypedTupleElement = 790 ''' <summary> ''' Represents an element of a tuple type supplying element name and optionally a type. ''' </summary> NamedTupleElement = 791 ''' <summary> ''' Trivia created when merge conflict markers (like "&lt;&lt;&lt;&lt;&lt;&lt;&lt;") are detected in source code ''' </summary> ConflictMarkerTrivia = 792 End Enum End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/VisualStudio/Core/Def/Implementation/UnusedReferences/ProjectAssets/ProjectAssetsFileReader.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Utilities; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets { internal static partial class ProjectAssetsFileReader { /// <summary> /// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy. /// </summary> public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync( ImmutableArray<ReferenceInfo> projectReferences, string projectAssetsFilePath) { var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath)); if (!doesProjectAssetsFileExist) { return ImmutableArray<ReferenceInfo>.Empty; } var projectAssetsFileContents = await IOUtilities.PerformIOAsync(async () => { using var fileStream = File.OpenRead(projectAssetsFilePath); using var reader = new StreamReader(fileStream); return await reader.ReadToEndAsync().ConfigureAwait(false); }).ConfigureAwait(false); if (projectAssetsFileContents is null) { return ImmutableArray<ReferenceInfo>.Empty; } try { var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents); return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets); } catch { return ImmutableArray<ReferenceInfo>.Empty; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Utilities; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets { internal static partial class ProjectAssetsFileReader { /// <summary> /// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy. /// </summary> public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync( ImmutableArray<ReferenceInfo> projectReferences, string projectAssetsFilePath) { var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath)); if (!doesProjectAssetsFileExist) { return ImmutableArray<ReferenceInfo>.Empty; } var projectAssetsFileContents = await IOUtilities.PerformIOAsync(async () => { using var fileStream = File.OpenRead(projectAssetsFilePath); using var reader = new StreamReader(fileStream); return await reader.ReadToEndAsync().ConfigureAwait(false); }).ConfigureAwait(false); if (projectAssetsFileContents is null) { return ImmutableArray<ReferenceInfo>.Empty; } try { var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents); return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets); } catch { return ImmutableArray<ReferenceInfo>.Empty; } } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Features/CSharp/Portable/SignatureHelp/PrimaryConstructorBaseTypeSignatureHelpProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { /// <summary> /// Implements SignatureHelp and ParameterInfo for <see cref="PrimaryConstructorBaseTypeSyntax"/> /// such as 'record Student(int Id) : Person($$"first", "last");`. /// </summary> [ExportSignatureHelpProvider("PrimaryConstructorBaseTypeSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class PrimaryConstructorBaseTypeSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PrimaryConstructorBaseTypeSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetBaseTypeSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out PrimaryConstructorBaseTypeSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; static bool IsArgumentListToken(PrimaryConstructorBaseTypeSyntax expression, SyntaxToken token) { return expression.ArgumentList != null && expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<PrimaryConstructorBaseTypeSyntax>(token, IsTriggerCharacter); protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (root is null || syntaxFacts is null || !TryGetBaseTypeSyntax(root, position, syntaxFacts, triggerInfo.TriggerReason, cancellationToken, out var baseTypeSyntax)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var baseType = semanticModel.GetTypeInfo(baseTypeSyntax.Type, cancellationToken).Type as INamedTypeSymbol; if (within is null || baseType is null) { return null; } var accessibleConstructors = baseType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within)) .WhereAsArray(c => c.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, baseTypeSyntax.SpanStart); if (!accessibleConstructors.Any()) { return null; } var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(baseTypeSyntax.ArgumentList); var currentConstructor = semanticModel.GetSymbolInfo(baseTypeSyntax, cancellationToken).Symbol; var selectedItem = TryGetSelectedIndex(accessibleConstructors, currentConstructor); return CreateSignatureHelpItems(accessibleConstructors.SelectAsArray(c => Convert(c, baseTypeSyntax.ArgumentList.OpenParenToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetBaseTypeSyntax(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } private static SignatureHelpItem Convert( IMethodSymbol constructor, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetPostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; static IList<SymbolDisplayPart> GetPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList(Punctuation(SyntaxKind.CloseParenToken)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { /// <summary> /// Implements SignatureHelp and ParameterInfo for <see cref="PrimaryConstructorBaseTypeSyntax"/> /// such as 'record Student(int Id) : Person($$"first", "last");`. /// </summary> [ExportSignatureHelpProvider("PrimaryConstructorBaseTypeSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class PrimaryConstructorBaseTypeSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PrimaryConstructorBaseTypeSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '(' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ')'; private bool TryGetBaseTypeSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out PrimaryConstructorBaseTypeSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; static bool IsArgumentListToken(PrimaryConstructorBaseTypeSyntax expression, SyntaxToken token) { return expression.ArgumentList != null && expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } } private bool IsTriggerToken(SyntaxToken token) => SignatureHelpUtilities.IsTriggerParenOrComma<PrimaryConstructorBaseTypeSyntax>(token, IsTriggerCharacter); protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (root is null || syntaxFacts is null || !TryGetBaseTypeSyntax(root, position, syntaxFacts, triggerInfo.TriggerReason, cancellationToken, out var baseTypeSyntax)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var baseType = semanticModel.GetTypeInfo(baseTypeSyntax.Type, cancellationToken).Type as INamedTypeSymbol; if (within is null || baseType is null) { return null; } var accessibleConstructors = baseType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within)) .WhereAsArray(c => c.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, baseTypeSyntax.SpanStart); if (!accessibleConstructors.Any()) { return null; } var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(baseTypeSyntax.ArgumentList); var currentConstructor = semanticModel.GetSymbolInfo(baseTypeSyntax, cancellationToken).Symbol; var selectedItem = TryGetSelectedIndex(accessibleConstructors, currentConstructor); return CreateSignatureHelpItems(accessibleConstructors.SelectAsArray(c => Convert(c, baseTypeSyntax.ArgumentList.OpenParenToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetBaseTypeSyntax(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } private static SignatureHelpItem Convert( IMethodSymbol constructor, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetPostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; static IList<SymbolDisplayPart> GetPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList(Punctuation(SyntaxKind.CloseParenToken)); } } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IEventReferenceOperation.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.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEvent() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() AddHandler E1, Sub(sender, args)'BIND:"E1" End Sub End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventWithInstanceReference() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c1Instance.E1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerInstanceEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_NoControlFlow() ' Verify event references with different kinds of instance references. Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Shared Event Event2 As EventHandler Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)'BIND:"Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)" AddHandler Me.Event1, handler1 AddHandler c.Event1, handler2 AddHandler Event2, handler3 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Me.Event1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me') Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C1) (Syntax: 'c') Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 2, handler3') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 2, handler3') Event Reference: IEventReferenceOperation: Event C1.Event2 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Event2') Instance Receiver: null Handler: IParameterReferenceOperation: handler3 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler3') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler) 'BIND:"Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler)" AddHandler If(c1, c2).Event1, handler End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... t1, handler') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... t1, handler') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c1, c2).Event1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Handler: IParameterReferenceOperation: handler (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver_StaticEvent() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Shared Event Event1 As EventHandler Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler) 'BIND:"Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler)" AddHandler c.Event1, handler1 AddHandler If(c, c2).Event1, handler2 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c, c2).Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c.Event1, handler1 ~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler If(c, c2).Event1, handler2 ~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEvent() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() AddHandler E1, Sub(sender, args)'BIND:"E1" End Sub End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventWithInstanceReference() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c1Instance.E1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerInstanceEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_NoControlFlow() ' Verify event references with different kinds of instance references. Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Shared Event Event2 As EventHandler Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)'BIND:"Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)" AddHandler Me.Event1, handler1 AddHandler c.Event1, handler2 AddHandler Event2, handler3 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Me.Event1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me') Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C1) (Syntax: 'c') Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 2, handler3') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 2, handler3') Event Reference: IEventReferenceOperation: Event C1.Event2 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Event2') Instance Receiver: null Handler: IParameterReferenceOperation: handler3 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler3') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler) 'BIND:"Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler)" AddHandler If(c1, c2).Event1, handler End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... t1, handler') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... t1, handler') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c1, c2).Event1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Handler: IParameterReferenceOperation: handler (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver_StaticEvent() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Shared Event Event1 As EventHandler Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler) 'BIND:"Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler)" AddHandler c.Event1, handler1 AddHandler If(c, c2).Event1, handler2 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c, c2).Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c.Event1, handler1 ~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler If(c, c2).Event1, handler2 ~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/Utilities/VarianceAmbiguity.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Utility functions to check if two implemented interfaces have variance ambiguity. ''' ''' What is "Variance Ambiguity"? Here's an example: ''' Class ReflectionType ''' Implements IEnumerable(Of Field) ''' Implements IEnumerable(Of Method) ''' Public Sub GetEnumeratorF() As IEnumerator(Of Field) Implements IEnumerable(Of Field).GetEnumerator ... ''' Public Sub GetEnumeratorM() As IEnumerator(Of Method) Implements IEnumerable(Of Method).GetEnumerator ... ''' End Class ''' Dim x as new ReflectionType ''' Dim y as IEnumerable(Of Member) = x ''' Dim z = y.GetEnumerator() ''' ''' Note that, through variance, both IEnumerable(Of Field) and IEnumerable(Of Method) have widening ''' conversions to IEnumerable(Of Member). So it's ambiguous whether the initialization of "z" would ''' invoke GetEnumeratorF or GetEnumeratorM. This function avoids such ambiguity at the declaration ''' level, i.e. it reports a warning on the two implements classes inside ReflectionType that they ''' may lead to ambiguity. ''' </summary> Friend Class VarianceAmbiguity ''' <summary> ''' Determine if two interfaces that were constructed from the same original definition ''' have variance ambiguity. ''' ''' We have something like left=ICocon(Of Mammal, int32[]), right=ICocon(Of Fish, int32[]) ''' for some interface ICocon(Of Out T, In U). And we have to decide if left and right ''' might lead to ambiguous member-lookup later on in execution. ''' ''' To do this: go through each type parameter T, U... ''' * For "Out T", judge whether the arguments Mammal/Fish cause ambiguity or prevent it. ''' * For "In T", judge whether the arguments int32[]/int32[] cause ambiguity or prevent it. ''' ''' "Causing/preventing ambiguity" is described further below. ''' ''' Given all that, ambiguity was prevented in any positions, then left/right are fine. ''' Otherwise, if ambiguity wasn't caused in any positions, then left/right are fine. ''' Otherwise, left/right have an ambiguity. ''' </summary> Public Shared Function HasVarianceAmbiguity(containingType As NamedTypeSymbol, i1 As NamedTypeSymbol, i2 As NamedTypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean Debug.Assert(i1.IsInterfaceType() AndAlso i2.IsInterfaceType()) Debug.Assert(i1.IsGenericType AndAlso i2.IsGenericType) Debug.Assert(TypeSymbol.Equals(i1.OriginalDefinition, i2.OriginalDefinition, TypeCompareKind.ConsiderEverything)) ' Go through all type arguments of all containing types. Order doesn't matters, so we ' go inside-out. Dim nestingType1 = i1 Dim nestingType2 = i2 Dim causesAmbiguity As Boolean = False Dim preventsAmbiguity As Boolean = False Do Dim arity = nestingType1.Arity For iTypeParameter = 0 To arity - 1 ' Below call passes "causesAmbiguity" and "preventsAmbiguity" by reference. CheckCorrespondingTypeArguments(containingType, nestingType1.TypeParameters(iTypeParameter).Variance, nestingType1.TypeArgumentWithDefinitionUseSiteDiagnostics(iTypeParameter, useSiteInfo), nestingType2.TypeArgumentWithDefinitionUseSiteDiagnostics(iTypeParameter, useSiteInfo), causesAmbiguity, preventsAmbiguity, useSiteInfo) Next nestingType1 = nestingType1.ContainingType nestingType2 = nestingType2.ContainingType Loop While nestingType1 IsNot Nothing ' If some type parameters caused ambiguity, and none prevented it, then we have an ambiguity. Return causesAmbiguity And Not preventsAmbiguity End Function ''' <summary> ''' Check two corresponding type arguments T1 and T2 and determine if the cause or prevent variable ambiguity. ''' ''' Identical types never cause or prevent ambiguity. ''' ''' If there could exist a **distinct** third type T3, such that T1 and T2 both convert via the variance ''' conversion to T3, then ambiguity is caused. This boils down to: ''' * Invariant parameters never cause ambiguity ''' * Covariant parameters "Out T": ambiguity is caused when the two type arguments ''' are non-object types not known to be values (T3=Object) ''' * Contravariant parameters "In U": ambiguity is caused when both: ''' - Neither T1 or T2 is a value type or a sealed (NotInheritable) reference type ''' - If T1 and T2 are both class types, one derives from the other. ''' (T3 is some type deriving or implementing both T1 and T2) ''' ''' Ambiguity is prevented when there T1 and T2 cannot unify to the same type, and there ''' cannot be a (not necessarily distinct) third type T3 that both T1 and T2 convert to via ''' the variance conversion. ''' ''' This boils down to: ''' * Invariant parameters: Ambiguity is prevented when: ''' - they are non-unifying ''' * Covariant parameters "Out T": Ambiguity is prevented when both: ''' - they are non-unifying ''' - at least one is a value type ''' * Contravariant parameters "In U": Ambiguity is prevented when: ''' - they are non-unifying AND ''' - at least one is known to be a value type OR ''' - both are known to be class types and neither derives from the other. ''' </summary> Private Shared Sub CheckCorrespondingTypeArguments(containingType As NamedTypeSymbol, variance As VarianceKind, typeArgument1 As TypeSymbol, typeArgument2 As TypeSymbol, ByRef causesAmbiguity As Boolean, ByRef preventsAmbiguity As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) If Not typeArgument1.IsSameTypeIgnoringAll(typeArgument2) Then Select Case variance Case VarianceKind.In Dim bothAreClasses = (typeArgument1.IsClassType() AndAlso typeArgument2.IsClassType()) Dim oneDerivesFromOther = bothAreClasses AndAlso (Conversions.ClassifyDirectCastConversion(typeArgument1, typeArgument2, useSiteInfo) And ConversionKind.Reference) <> 0 ' (Note that value types are always NotInheritable) If Not typeArgument1.IsNotInheritable() AndAlso Not typeArgument2.IsNotInheritable() AndAlso (Not bothAreClasses OrElse oneDerivesFromOther) Then causesAmbiguity = True ElseIf (typeArgument1.IsValueType OrElse typeArgument2.IsValueType OrElse (bothAreClasses AndAlso Not oneDerivesFromOther)) AndAlso Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case VarianceKind.Out If typeArgument1.SpecialType <> SpecialType.System_Object AndAlso typeArgument2.SpecialType <> SpecialType.System_Object AndAlso Not typeArgument1.IsValueType AndAlso Not typeArgument2.IsValueType Then causesAmbiguity = True ElseIf (typeArgument1.IsValueType OrElse typeArgument2.IsValueType) AndAlso Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case VarianceKind.None If Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case Else Throw ExceptionUtilities.UnexpectedValue(variance) End Select 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Utility functions to check if two implemented interfaces have variance ambiguity. ''' ''' What is "Variance Ambiguity"? Here's an example: ''' Class ReflectionType ''' Implements IEnumerable(Of Field) ''' Implements IEnumerable(Of Method) ''' Public Sub GetEnumeratorF() As IEnumerator(Of Field) Implements IEnumerable(Of Field).GetEnumerator ... ''' Public Sub GetEnumeratorM() As IEnumerator(Of Method) Implements IEnumerable(Of Method).GetEnumerator ... ''' End Class ''' Dim x as new ReflectionType ''' Dim y as IEnumerable(Of Member) = x ''' Dim z = y.GetEnumerator() ''' ''' Note that, through variance, both IEnumerable(Of Field) and IEnumerable(Of Method) have widening ''' conversions to IEnumerable(Of Member). So it's ambiguous whether the initialization of "z" would ''' invoke GetEnumeratorF or GetEnumeratorM. This function avoids such ambiguity at the declaration ''' level, i.e. it reports a warning on the two implements classes inside ReflectionType that they ''' may lead to ambiguity. ''' </summary> Friend Class VarianceAmbiguity ''' <summary> ''' Determine if two interfaces that were constructed from the same original definition ''' have variance ambiguity. ''' ''' We have something like left=ICocon(Of Mammal, int32[]), right=ICocon(Of Fish, int32[]) ''' for some interface ICocon(Of Out T, In U). And we have to decide if left and right ''' might lead to ambiguous member-lookup later on in execution. ''' ''' To do this: go through each type parameter T, U... ''' * For "Out T", judge whether the arguments Mammal/Fish cause ambiguity or prevent it. ''' * For "In T", judge whether the arguments int32[]/int32[] cause ambiguity or prevent it. ''' ''' "Causing/preventing ambiguity" is described further below. ''' ''' Given all that, ambiguity was prevented in any positions, then left/right are fine. ''' Otherwise, if ambiguity wasn't caused in any positions, then left/right are fine. ''' Otherwise, left/right have an ambiguity. ''' </summary> Public Shared Function HasVarianceAmbiguity(containingType As NamedTypeSymbol, i1 As NamedTypeSymbol, i2 As NamedTypeSymbol, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean Debug.Assert(i1.IsInterfaceType() AndAlso i2.IsInterfaceType()) Debug.Assert(i1.IsGenericType AndAlso i2.IsGenericType) Debug.Assert(TypeSymbol.Equals(i1.OriginalDefinition, i2.OriginalDefinition, TypeCompareKind.ConsiderEverything)) ' Go through all type arguments of all containing types. Order doesn't matters, so we ' go inside-out. Dim nestingType1 = i1 Dim nestingType2 = i2 Dim causesAmbiguity As Boolean = False Dim preventsAmbiguity As Boolean = False Do Dim arity = nestingType1.Arity For iTypeParameter = 0 To arity - 1 ' Below call passes "causesAmbiguity" and "preventsAmbiguity" by reference. CheckCorrespondingTypeArguments(containingType, nestingType1.TypeParameters(iTypeParameter).Variance, nestingType1.TypeArgumentWithDefinitionUseSiteDiagnostics(iTypeParameter, useSiteInfo), nestingType2.TypeArgumentWithDefinitionUseSiteDiagnostics(iTypeParameter, useSiteInfo), causesAmbiguity, preventsAmbiguity, useSiteInfo) Next nestingType1 = nestingType1.ContainingType nestingType2 = nestingType2.ContainingType Loop While nestingType1 IsNot Nothing ' If some type parameters caused ambiguity, and none prevented it, then we have an ambiguity. Return causesAmbiguity And Not preventsAmbiguity End Function ''' <summary> ''' Check two corresponding type arguments T1 and T2 and determine if the cause or prevent variable ambiguity. ''' ''' Identical types never cause or prevent ambiguity. ''' ''' If there could exist a **distinct** third type T3, such that T1 and T2 both convert via the variance ''' conversion to T3, then ambiguity is caused. This boils down to: ''' * Invariant parameters never cause ambiguity ''' * Covariant parameters "Out T": ambiguity is caused when the two type arguments ''' are non-object types not known to be values (T3=Object) ''' * Contravariant parameters "In U": ambiguity is caused when both: ''' - Neither T1 or T2 is a value type or a sealed (NotInheritable) reference type ''' - If T1 and T2 are both class types, one derives from the other. ''' (T3 is some type deriving or implementing both T1 and T2) ''' ''' Ambiguity is prevented when there T1 and T2 cannot unify to the same type, and there ''' cannot be a (not necessarily distinct) third type T3 that both T1 and T2 convert to via ''' the variance conversion. ''' ''' This boils down to: ''' * Invariant parameters: Ambiguity is prevented when: ''' - they are non-unifying ''' * Covariant parameters "Out T": Ambiguity is prevented when both: ''' - they are non-unifying ''' - at least one is a value type ''' * Contravariant parameters "In U": Ambiguity is prevented when: ''' - they are non-unifying AND ''' - at least one is known to be a value type OR ''' - both are known to be class types and neither derives from the other. ''' </summary> Private Shared Sub CheckCorrespondingTypeArguments(containingType As NamedTypeSymbol, variance As VarianceKind, typeArgument1 As TypeSymbol, typeArgument2 As TypeSymbol, ByRef causesAmbiguity As Boolean, ByRef preventsAmbiguity As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) If Not typeArgument1.IsSameTypeIgnoringAll(typeArgument2) Then Select Case variance Case VarianceKind.In Dim bothAreClasses = (typeArgument1.IsClassType() AndAlso typeArgument2.IsClassType()) Dim oneDerivesFromOther = bothAreClasses AndAlso (Conversions.ClassifyDirectCastConversion(typeArgument1, typeArgument2, useSiteInfo) And ConversionKind.Reference) <> 0 ' (Note that value types are always NotInheritable) If Not typeArgument1.IsNotInheritable() AndAlso Not typeArgument2.IsNotInheritable() AndAlso (Not bothAreClasses OrElse oneDerivesFromOther) Then causesAmbiguity = True ElseIf (typeArgument1.IsValueType OrElse typeArgument2.IsValueType OrElse (bothAreClasses AndAlso Not oneDerivesFromOther)) AndAlso Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case VarianceKind.Out If typeArgument1.SpecialType <> SpecialType.System_Object AndAlso typeArgument2.SpecialType <> SpecialType.System_Object AndAlso Not typeArgument1.IsValueType AndAlso Not typeArgument2.IsValueType Then causesAmbiguity = True ElseIf (typeArgument1.IsValueType OrElse typeArgument2.IsValueType) AndAlso Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case VarianceKind.None If Not TypeUnification.CanUnify(containingType, typeArgument1, typeArgument2) Then preventsAmbiguity = True End If Case Else Throw ExceptionUtilities.UnexpectedValue(variance) End Select End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.ConditionalSymbolsMap.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.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports PreprocessorState = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner.PreprocessorState Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' Map containing information about all conditional symbol definitions in the source file corresponding to a parsed syntax tree. ''' </summary> Private Class ConditionalSymbolsMap ''' <summary> ''' Conditional symbols map, where each key-value pair indicates: ''' Key: Conditional symbol name. ''' Value: Stack of all active conditional symbol definitions, i.e. #Const directives, in the source file corresponding to a parsed syntax tree. ''' All the defining #Const directives for a conditional symbol are pushed onto this stack in source code order. ''' Each stack entry is a tuple {InternalSyntax.CConst, Integer} where: ''' InternalSyntax.CConst: Constant value of the symbol. ''' Integer: Source position of the defining #Const directive. ''' </summary> Private ReadOnly _conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Friend Shared ReadOnly Uninitialized As ConditionalSymbolsMap = New ConditionalSymbolsMap() ' Only used by Uninitialized instance Private Sub New() End Sub Private Sub New(conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))) Debug.Assert(conditionalsMap IsNot Nothing) Debug.Assert(conditionalsMap.Any()) #If DEBUG Then For Each kvPair In conditionalsMap Dim conditionalStack As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = kvPair.Value Debug.Assert(conditionalStack.Any()) ' Ensure that all the defining #Const directives for this conditional symbol are pushed onto the stack in source code order. Dim prevPosition As Integer = Int32.MaxValue For i = 0 To conditionalStack.Count - 1 Dim position As Integer = conditionalStack(i).Item2 Debug.Assert(prevPosition >= position) prevPosition = position Next Next #End If Me._conditionalsMap = conditionalsMap End Sub #Region "Build conditional symbols map" Friend Shared Function Create(syntaxRoot As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As ConditionalSymbolsMap Dim symbolsMapBuilder = New ConditionalSymbolsMapBuilder() Dim conditionalSymbolsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) = symbolsMapBuilder.Build(syntaxRoot, options) Debug.Assert(conditionalSymbolsMap Is Nothing OrElse conditionalSymbolsMap.Count > 0) Return If(conditionalSymbolsMap IsNot Nothing, New ConditionalSymbolsMap(conditionalSymbolsMap), Nothing) End Function Private Class ConditionalSymbolsMapBuilder Private _conditionalsMap As Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Private _preprocessorState As PreprocessorState Friend Function Build(root As SyntaxNodeOrToken, options As VisualBasicParseOptions) As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Me._conditionalsMap = New Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))(IdentifierComparison.Comparer) ' Process command line preprocessor symbol definitions. Dim preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst) = Scanner.GetPreprocessorConstants(options) Me.ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap) Me._preprocessorState = New PreprocessorState(preprocessorSymbolsMap) ' Get and process source directives. Dim directives As IEnumerable(Of DirectiveTriviaSyntax) = root.GetDirectives(Of DirectiveTriviaSyntax)() Debug.Assert(directives IsNot Nothing) ProcessSourceDirectives(directives) Return If(Me._conditionalsMap.Any(), ImmutableDictionary.CreateRange(IdentifierComparison.Comparer, Me._conditionalsMap), Nothing) End Function Private Sub ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst)) For Each kvPair In preprocessorSymbolsMap Me.ProcessConditionalSymbolDefinition(kvPair.Key, kvPair.Value, 0) Next End Sub Private Sub ProcessConditionalSymbolDefinition(name As String, value As InternalSyntax.CConst, position As Integer) Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. values = New Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) _conditionalsMap.Add(name, values) End If values.Push(Tuple.Create(value, position)) End Sub Private Sub ProcessSourceDirectives(directives As IEnumerable(Of DirectiveTriviaSyntax)) For Each directive In directives ProcessDirective(directive) Next End Sub ' Process all active conditional directives under trivia, in source code order. Private Sub ProcessDirective(directive As DirectiveTriviaSyntax) Debug.Assert(_conditionalsMap IsNot Nothing) Debug.Assert(directive IsNot Nothing) Select Case directive.Kind Case SyntaxKind.ConstDirectiveTrivia Dim prevPreprocessorSymbols = _preprocessorState.SymbolsMap _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) Dim newPreprocessorSymbols = _preprocessorState.SymbolsMap If Not prevPreprocessorSymbols Is newPreprocessorSymbols Then Dim name As String = DirectCast(directive, ConstDirectiveTriviaSyntax).Name.ValueText #If DEBUG Then Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. Debug.Assert(Not prevPreprocessorSymbols.ContainsKey(name)) Else ' Not the first definition for this conditional symbol in this source file. ' We must have an existing entry for this conditional symbol in prevPreprocessorSymbols map. Debug.Assert(values IsNot Nothing) Debug.Assert(prevPreprocessorSymbols.ContainsKey(name)) Debug.Assert(Object.Equals(prevPreprocessorSymbols(name).ValueAsObject, values.Peek().Item1.ValueAsObject)) End If #End If ProcessConditionalSymbolDefinition(name, newPreprocessorSymbols(name), directive.SpanStart) End If Case Else _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) End Select End Sub End Class #End Region Friend Function GetPreprocessingSymbolInfo(conditionalSymbolName As String, node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue Is Nothing Then Return VisualBasicPreprocessingSymbolInfo.None End If ' Get symbol name at preprocessor definition, i.e. #Const directive. ' NOTE: symbolName and conditionalSymbolName might have different case, we want the definition name. Dim symbolName = _conditionalsMap.Keys.First(Function(key) IdentifierComparison.Equals(key, conditionalSymbolName)) Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(name:=symbolName), constantValueOpt:=constValue.ValueAsObject, isDefined:=True) End Function Private Function GetPreprocessorSymbolValue(conditionalSymbolName As String, node As SyntaxNodeOrToken) As InternalSyntax.CConst Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If _conditionalsMap.TryGetValue(conditionalSymbolName, values) Then ' All the defining #Const directives for a conditional symbol are pushed onto the stack in source code order. ' Get the first entry from the top end of the stack with source position less then the source position of 'node'. ' If there is none, then the given conditional symbol is undefined at 'node' Dim position As Integer = node.SpanStart For Each valueTuple In values If valueTuple.Item2 < position Then Return valueTuple.Item1 End If Next End If Return Nothing End Function ' Returns a flag indicating whether the given conditional symbol is defined prior to the given node in source code order in this parsed syntax tree and ' it has a non-zero integral value or non-null string value. ' NOTE: These criteria are used by the native VB compiler. Friend Function IsConditionalSymbolDefined(conditionalSymbolName As String, node As SyntaxNodeOrToken) As Boolean If conditionalSymbolName IsNot Nothing Then Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue IsNot Nothing AndAlso Not constValue.IsBad Then Select Case constValue.SpecialType Case SpecialType.System_Boolean Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Boolean)) Return value.Value Case SpecialType.System_Byte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Byte)) Return value.Value <> 0 Case SpecialType.System_Int16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int16)) Return value.Value <> 0 Case SpecialType.System_Int32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int32)) Return value.Value <> 0 Case SpecialType.System_Int64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int64)) Return value.Value <> 0 Case SpecialType.System_SByte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of SByte)) Return value.Value <> 0 Case SpecialType.System_UInt16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt16)) Return value.Value <> 0 Case SpecialType.System_UInt32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt32)) Return value.Value <> 0 Case SpecialType.System_UInt64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt64)) Return value.Value <> 0 Case SpecialType.System_String Debug.Assert(DirectCast(constValue, InternalSyntax.CConst(Of String)).Value IsNot Nothing) Return True End Select End If End If Return False End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports PreprocessorState = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner.PreprocessorState Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' Map containing information about all conditional symbol definitions in the source file corresponding to a parsed syntax tree. ''' </summary> Private Class ConditionalSymbolsMap ''' <summary> ''' Conditional symbols map, where each key-value pair indicates: ''' Key: Conditional symbol name. ''' Value: Stack of all active conditional symbol definitions, i.e. #Const directives, in the source file corresponding to a parsed syntax tree. ''' All the defining #Const directives for a conditional symbol are pushed onto this stack in source code order. ''' Each stack entry is a tuple {InternalSyntax.CConst, Integer} where: ''' InternalSyntax.CConst: Constant value of the symbol. ''' Integer: Source position of the defining #Const directive. ''' </summary> Private ReadOnly _conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Friend Shared ReadOnly Uninitialized As ConditionalSymbolsMap = New ConditionalSymbolsMap() ' Only used by Uninitialized instance Private Sub New() End Sub Private Sub New(conditionalsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))) Debug.Assert(conditionalsMap IsNot Nothing) Debug.Assert(conditionalsMap.Any()) #If DEBUG Then For Each kvPair In conditionalsMap Dim conditionalStack As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = kvPair.Value Debug.Assert(conditionalStack.Any()) ' Ensure that all the defining #Const directives for this conditional symbol are pushed onto the stack in source code order. Dim prevPosition As Integer = Int32.MaxValue For i = 0 To conditionalStack.Count - 1 Dim position As Integer = conditionalStack(i).Item2 Debug.Assert(prevPosition >= position) prevPosition = position Next Next #End If Me._conditionalsMap = conditionalsMap End Sub #Region "Build conditional symbols map" Friend Shared Function Create(syntaxRoot As VisualBasicSyntaxNode, options As VisualBasicParseOptions) As ConditionalSymbolsMap Dim symbolsMapBuilder = New ConditionalSymbolsMapBuilder() Dim conditionalSymbolsMap As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) = symbolsMapBuilder.Build(syntaxRoot, options) Debug.Assert(conditionalSymbolsMap Is Nothing OrElse conditionalSymbolsMap.Count > 0) Return If(conditionalSymbolsMap IsNot Nothing, New ConditionalSymbolsMap(conditionalSymbolsMap), Nothing) End Function Private Class ConditionalSymbolsMapBuilder Private _conditionalsMap As Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Private _preprocessorState As PreprocessorState Friend Function Build(root As SyntaxNodeOrToken, options As VisualBasicParseOptions) As ImmutableDictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer))) Me._conditionalsMap = New Dictionary(Of String, Stack(Of Tuple(Of InternalSyntax.CConst, Integer)))(IdentifierComparison.Comparer) ' Process command line preprocessor symbol definitions. Dim preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst) = Scanner.GetPreprocessorConstants(options) Me.ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap) Me._preprocessorState = New PreprocessorState(preprocessorSymbolsMap) ' Get and process source directives. Dim directives As IEnumerable(Of DirectiveTriviaSyntax) = root.GetDirectives(Of DirectiveTriviaSyntax)() Debug.Assert(directives IsNot Nothing) ProcessSourceDirectives(directives) Return If(Me._conditionalsMap.Any(), ImmutableDictionary.CreateRange(IdentifierComparison.Comparer, Me._conditionalsMap), Nothing) End Function Private Sub ProcessCommandLinePreprocessorSymbols(preprocessorSymbolsMap As ImmutableDictionary(Of String, InternalSyntax.CConst)) For Each kvPair In preprocessorSymbolsMap Me.ProcessConditionalSymbolDefinition(kvPair.Key, kvPair.Value, 0) Next End Sub Private Sub ProcessConditionalSymbolDefinition(name As String, value As InternalSyntax.CConst, position As Integer) Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. values = New Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) _conditionalsMap.Add(name, values) End If values.Push(Tuple.Create(value, position)) End Sub Private Sub ProcessSourceDirectives(directives As IEnumerable(Of DirectiveTriviaSyntax)) For Each directive In directives ProcessDirective(directive) Next End Sub ' Process all active conditional directives under trivia, in source code order. Private Sub ProcessDirective(directive As DirectiveTriviaSyntax) Debug.Assert(_conditionalsMap IsNot Nothing) Debug.Assert(directive IsNot Nothing) Select Case directive.Kind Case SyntaxKind.ConstDirectiveTrivia Dim prevPreprocessorSymbols = _preprocessorState.SymbolsMap _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) Dim newPreprocessorSymbols = _preprocessorState.SymbolsMap If Not prevPreprocessorSymbols Is newPreprocessorSymbols Then Dim name As String = DirectCast(directive, ConstDirectiveTriviaSyntax).Name.ValueText #If DEBUG Then Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If Not _conditionalsMap.TryGetValue(name, values) Then ' First definition for this conditional symbol in this source file, create a new key-value pair. Debug.Assert(Not prevPreprocessorSymbols.ContainsKey(name)) Else ' Not the first definition for this conditional symbol in this source file. ' We must have an existing entry for this conditional symbol in prevPreprocessorSymbols map. Debug.Assert(values IsNot Nothing) Debug.Assert(prevPreprocessorSymbols.ContainsKey(name)) Debug.Assert(Object.Equals(prevPreprocessorSymbols(name).ValueAsObject, values.Peek().Item1.ValueAsObject)) End If #End If ProcessConditionalSymbolDefinition(name, newPreprocessorSymbols(name), directive.SpanStart) End If Case Else _preprocessorState = Scanner.ApplyDirective(_preprocessorState, DirectCast(directive.Green(), InternalSyntax.DirectiveTriviaSyntax)) End Select End Sub End Class #End Region Friend Function GetPreprocessingSymbolInfo(conditionalSymbolName As String, node As IdentifierNameSyntax) As VisualBasicPreprocessingSymbolInfo Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue Is Nothing Then Return VisualBasicPreprocessingSymbolInfo.None End If ' Get symbol name at preprocessor definition, i.e. #Const directive. ' NOTE: symbolName and conditionalSymbolName might have different case, we want the definition name. Dim symbolName = _conditionalsMap.Keys.First(Function(key) IdentifierComparison.Equals(key, conditionalSymbolName)) Return New VisualBasicPreprocessingSymbolInfo(New PreprocessingSymbol(name:=symbolName), constantValueOpt:=constValue.ValueAsObject, isDefined:=True) End Function Private Function GetPreprocessorSymbolValue(conditionalSymbolName As String, node As SyntaxNodeOrToken) As InternalSyntax.CConst Dim values As Stack(Of Tuple(Of InternalSyntax.CConst, Integer)) = Nothing If _conditionalsMap.TryGetValue(conditionalSymbolName, values) Then ' All the defining #Const directives for a conditional symbol are pushed onto the stack in source code order. ' Get the first entry from the top end of the stack with source position less then the source position of 'node'. ' If there is none, then the given conditional symbol is undefined at 'node' Dim position As Integer = node.SpanStart For Each valueTuple In values If valueTuple.Item2 < position Then Return valueTuple.Item1 End If Next End If Return Nothing End Function ' Returns a flag indicating whether the given conditional symbol is defined prior to the given node in source code order in this parsed syntax tree and ' it has a non-zero integral value or non-null string value. ' NOTE: These criteria are used by the native VB compiler. Friend Function IsConditionalSymbolDefined(conditionalSymbolName As String, node As SyntaxNodeOrToken) As Boolean If conditionalSymbolName IsNot Nothing Then Dim constValue As InternalSyntax.CConst = GetPreprocessorSymbolValue(conditionalSymbolName, node) If constValue IsNot Nothing AndAlso Not constValue.IsBad Then Select Case constValue.SpecialType Case SpecialType.System_Boolean Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Boolean)) Return value.Value Case SpecialType.System_Byte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Byte)) Return value.Value <> 0 Case SpecialType.System_Int16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int16)) Return value.Value <> 0 Case SpecialType.System_Int32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int32)) Return value.Value <> 0 Case SpecialType.System_Int64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of Int64)) Return value.Value <> 0 Case SpecialType.System_SByte Dim value = DirectCast(constValue, InternalSyntax.CConst(Of SByte)) Return value.Value <> 0 Case SpecialType.System_UInt16 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt16)) Return value.Value <> 0 Case SpecialType.System_UInt32 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt32)) Return value.Value <> 0 Case SpecialType.System_UInt64 Dim value = DirectCast(constValue, InternalSyntax.CConst(Of UInt64)) Return value.Value <> 0 Case SpecialType.System_String Debug.Assert(DirectCast(constValue, InternalSyntax.CConst(Of String)).Value IsNot Nothing) Return True End Select End If End If Return False End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/DuplicatedGuidLibrary4.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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Library2</RootNamespace> <AssemblyName>Library2</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Library2</RootNamespace> <AssemblyName>Library2</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Test/PdbUtilities/Shared/StringUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using System.Text; namespace Roslyn.Test { internal static class StringUtilities { internal static string EscapeNonPrintableCharacters(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { bool escape; switch (CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.Control: case UnicodeCategory.OtherNotAssigned: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Surrogate: escape = true; break; default: escape = c >= 0xFFFC; break; } if (escape) { sb.AppendFormat("\\u{0:X4}", (int)c); } else { sb.Append(c); } } return sb.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.Globalization; using System.Text; namespace Roslyn.Test { internal static class StringUtilities { internal static string EscapeNonPrintableCharacters(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { bool escape; switch (CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.Control: case UnicodeCategory.OtherNotAssigned: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Surrogate: escape = true; break; default: escape = c >= 0xFFFC; break; } if (escape) { sb.AppendFormat("\\u{0:X4}", (int)c); } else { sb.Append(c); } } return sb.ToString(); } } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/LocalSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class LocalSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILocalSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) => t => IdentifiersMatch(syntaxFacts, name, t); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class LocalSymbolReferenceFinder : AbstractMemberScopedReferenceFinder<ILocalSymbol> { protected override Func<SyntaxToken, bool> GetTokensMatchFunction(ISyntaxFactsService syntaxFacts, string name) => t => IdentifiersMatch(syntaxFacts, name, t); } }
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.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.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Manages anonymous types and delegates created on module level. All requests ''' for anonymous type/delegate symbols go via the instance of this class. ''' ''' Manager also is in charge of creating implementation types which are used in ''' emit phase to substitute anonymous type/delegate public symbols. ''' </summary> Partial Friend NotInheritable Class AnonymousTypeManager Inherits CommonAnonymousTypeManager ''' <summary> Source module </summary> Public ReadOnly Property ContainingModule As SourceModuleSymbol Get Return DirectCast(Compilation.SourceModule, SourceModuleSymbol) End Get End Property ''' <summary> Owning compilationSource module </summary> Public ReadOnly Compilation As VisualBasicCompilation Public Sub New(compilation As VisualBasicCompilation) Me.Compilation = compilation End Sub ''' <summary> ''' Given anonymous type descriptor provided construct an anonymous type symbol ''' </summary> Public Function ConstructAnonymousTypeSymbol(typeDescr As AnonymousTypeDescriptor) As AnonymousTypePublicSymbol Return New AnonymousTypePublicSymbol(Me, typeDescr) End Function ''' <summary> ''' Given anonymous delegate descriptor provided, construct an anonymous delegate symbol ''' </summary> Public Function ConstructAnonymousDelegateSymbol(delegateDescriptor As AnonymousTypeDescriptor) As AnonymousDelegatePublicSymbol Return New AnonymousDelegatePublicSymbol(Me, delegateDescriptor) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Manages anonymous types and delegates created on module level. All requests ''' for anonymous type/delegate symbols go via the instance of this class. ''' ''' Manager also is in charge of creating implementation types which are used in ''' emit phase to substitute anonymous type/delegate public symbols. ''' </summary> Partial Friend NotInheritable Class AnonymousTypeManager Inherits CommonAnonymousTypeManager ''' <summary> Source module </summary> Public ReadOnly Property ContainingModule As SourceModuleSymbol Get Return DirectCast(Compilation.SourceModule, SourceModuleSymbol) End Get End Property ''' <summary> Owning compilationSource module </summary> Public ReadOnly Compilation As VisualBasicCompilation Public Sub New(compilation As VisualBasicCompilation) Me.Compilation = compilation End Sub ''' <summary> ''' Given anonymous type descriptor provided construct an anonymous type symbol ''' </summary> Public Function ConstructAnonymousTypeSymbol(typeDescr As AnonymousTypeDescriptor) As AnonymousTypePublicSymbol Return New AnonymousTypePublicSymbol(Me, typeDescr) End Function ''' <summary> ''' Given anonymous delegate descriptor provided, construct an anonymous delegate symbol ''' </summary> Public Function ConstructAnonymousDelegateSymbol(delegateDescriptor As AnonymousTypeDescriptor) As AnonymousDelegatePublicSymbol Return New AnonymousDelegatePublicSymbol(Me, delegateDescriptor) End Function End Class End Namespace
-1
dotnet/roslyn
55,713
Don't add accessibility modifiers to partial classes in new documents
Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
davidwengier
2021-08-18T23:34:29Z
2021-08-20T04:00:24Z
439cd0e252559a2d8fcd36723e1a2ef350c810b5
7c6289ac905f702fa4398067b91cf29a80e4692a
Don't add accessibility modifiers to partial classes in new documents. Fixes https://github.com/dotnet/roslyn/issues/55703 Unfortunately we don't have enough information to go on when processing new documents to do anything smarter here :(
./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter_Serialization.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter : IObjectWritable { private const string SerializationFormat = "2"; bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { writer.WriteString(SerializationFormat); writer.WriteBoolean(_isCaseSensitive); writer.WriteInt32(_hashFunctionCount); WriteBitArray(writer, _bitArray); } private static void WriteBitArray(ObjectWriter writer, BitArray bitArray) { // Our serialization format doesn't round-trip bit arrays of non-byte lengths Contract.ThrowIfTrue(bitArray.Length % 8 != 0); writer.WriteInt32(bitArray.Length / 8); // This will hold the byte that we will write out after we process every 8 bits. This is // LSB, so we push bits into it from the MSB. byte b = 0; for (var i = 0; i < bitArray.Length; i++) { if (bitArray[i]) { b = (byte)(0x80 | b >> 1); } else { b >>= 1; } if ((i + 1) % 8 == 0) { // End of a byte, write out the byte writer.WriteByte(b); } } } public static BloomFilter ReadFrom(ObjectReader reader) { var version = reader.ReadString(); if (!string.Equals(version, SerializationFormat, StringComparison.Ordinal)) { return null; } var isCaseSensitive = reader.ReadBoolean(); var hashFunctionCount = reader.ReadInt32(); var bitArray = ReadBitArray(reader); return new BloomFilter(bitArray, hashFunctionCount, isCaseSensitive); } private static BitArray ReadBitArray(ObjectReader reader) { // TODO: find a way to use pool var length = reader.ReadInt32(); var bytes = new byte[length]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = reader.ReadByte(); } return new BitArray(bytes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter : IObjectWritable { private const string SerializationFormat = "2"; bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { writer.WriteString(SerializationFormat); writer.WriteBoolean(_isCaseSensitive); writer.WriteInt32(_hashFunctionCount); WriteBitArray(writer, _bitArray); } private static void WriteBitArray(ObjectWriter writer, BitArray bitArray) { // Our serialization format doesn't round-trip bit arrays of non-byte lengths Contract.ThrowIfTrue(bitArray.Length % 8 != 0); writer.WriteInt32(bitArray.Length / 8); // This will hold the byte that we will write out after we process every 8 bits. This is // LSB, so we push bits into it from the MSB. byte b = 0; for (var i = 0; i < bitArray.Length; i++) { if (bitArray[i]) { b = (byte)(0x80 | b >> 1); } else { b >>= 1; } if ((i + 1) % 8 == 0) { // End of a byte, write out the byte writer.WriteByte(b); } } } public static BloomFilter ReadFrom(ObjectReader reader) { var version = reader.ReadString(); if (!string.Equals(version, SerializationFormat, StringComparison.Ordinal)) { return null; } var isCaseSensitive = reader.ReadBoolean(); var hashFunctionCount = reader.ReadInt32(); var bitArray = ReadBitArray(reader); return new BloomFilter(bitArray, hashFunctionCount, isCaseSensitive); } private static BitArray ReadBitArray(ObjectReader reader) { // TODO: find a way to use pool var length = reader.ReadInt32(); var bytes = new byte[length]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = reader.ReadByte(); } return new BitArray(bytes); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/GoToDefinition/GoToDefinitionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal static class GoToDefinitionHelpers { public static ImmutableArray<DefinitionItem> GetDefinitions( ISymbol symbol, Solution solution, bool thirdPartyNavigationAllowed, CancellationToken cancellationToken) { var alias = symbol as IAliasSymbol; if (alias != null) { if (alias.Target is INamespaceSymbol ns && ns.IsGlobalNamespace) { return ImmutableArray.Create<DefinitionItem>(); } } // VB global import aliases have a synthesized SyntaxTree. // We can't go to the definition of the alias, so use the target type. if (alias != null) { var sourceLocations = NavigableItemFactory.GetPreferredSourceLocations( solution, symbol, cancellationToken); if (sourceLocations.All(l => solution.GetDocument(l.SourceTree) == null)) { symbol = alias.Target; } } var definition = SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).WaitAndGetResult(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); symbol = definition ?? symbol; // If it is a partial method declaration with no body, choose to go to the implementation // that has a method body. if (symbol is IMethodSymbol method) { symbol = method.PartialImplementationPart ?? symbol; } using var definitionsDisposer = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); // Going to a symbol may end up actually showing the symbol in the Find-Usages window. // This happens when there is more than one location for the symbol (i.e. for partial // symbols) and we don't know the best place to take you to. // // The FindUsages window supports showing the classified text for an item. It does this // in two ways. Either the item can pass along its classified text (and the window will // defer to that), or the item will have no classified text, and the window will compute // it in the BG. // // Passing along the classified information is valuable for OOP scenarios where we want // all that expensive computation done on the OOP side and not in the VS side. // // However, Go To Definition is all in-process, and is also synchronous. So we do not // want to fetch the classifications here. It slows down the command and leads to a // measurable delay in our perf tests. // // So, if we only have a single location to go to, this does no unnecessary work. And, // if we do have multiple locations to show, it will just be done in the BG, unblocking // this command thread so it can return the user faster. var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (thirdPartyNavigationAllowed) { var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>(); var thirdPartyItem = factory?.GetThirdPartyDefinitionItem(solution, definitionItem, cancellationToken); definitions.AddIfNotNull(thirdPartyItem); } definitions.Add(definitionItem); return definitions.ToImmutable(); } public static bool TryGoToDefinition( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { var definitions = GetDefinitions(symbol, solution, thirdPartyNavigationAllowed, cancellationToken); var title = string.Format(EditorFeaturesResources._0_declarations, FindUsagesHelpers.GetDisplayName(symbol)); return threadingContext.JoinableTaskFactory.Run( () => streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, cancellationToken)); } public static bool TryGoToDefinition( ImmutableArray<DefinitionItem> definitions, Solution solution, string title, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken) { if (definitions.IsDefaultOrEmpty) return false; return threadingContext.JoinableTaskFactory.Run(() => streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, cancellationToken)); } public static bool TryGoToDefinition( ImmutableArray<DefinitionItem> definitions, Workspace workspace, string title, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken) { if (definitions.IsDefaultOrEmpty) return false; return threadingContext.JoinableTaskFactory.Run(() => streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, workspace, title, definitions, 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.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal static class GoToDefinitionHelpers { public static ImmutableArray<DefinitionItem> GetDefinitions( ISymbol symbol, Solution solution, bool thirdPartyNavigationAllowed, CancellationToken cancellationToken) { var alias = symbol as IAliasSymbol; if (alias != null) { if (alias.Target is INamespaceSymbol ns && ns.IsGlobalNamespace) { return ImmutableArray.Create<DefinitionItem>(); } } // VB global import aliases have a synthesized SyntaxTree. // We can't go to the definition of the alias, so use the target type. if (alias != null) { var sourceLocations = NavigableItemFactory.GetPreferredSourceLocations( solution, symbol, cancellationToken); if (sourceLocations.All(l => solution.GetDocument(l.SourceTree) == null)) { symbol = alias.Target; } } var definition = SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).WaitAndGetResult(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); symbol = definition ?? symbol; // If it is a partial method declaration with no body, choose to go to the implementation // that has a method body. if (symbol is IMethodSymbol method) { symbol = method.PartialImplementationPart ?? symbol; } using var definitionsDisposer = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); // Going to a symbol may end up actually showing the symbol in the Find-Usages window. // This happens when there is more than one location for the symbol (i.e. for partial // symbols) and we don't know the best place to take you to. // // The FindUsages window supports showing the classified text for an item. It does this // in two ways. Either the item can pass along its classified text (and the window will // defer to that), or the item will have no classified text, and the window will compute // it in the BG. // // Passing along the classified information is valuable for OOP scenarios where we want // all that expensive computation done on the OOP side and not in the VS side. // // However, Go To Definition is all in-process, and is also synchronous. So we do not // want to fetch the classifications here. It slows down the command and leads to a // measurable delay in our perf tests. // // So, if we only have a single location to go to, this does no unnecessary work. And, // if we do have multiple locations to show, it will just be done in the BG, unblocking // this command thread so it can return the user faster. var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (thirdPartyNavigationAllowed) { var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>(); var thirdPartyItem = factory?.GetThirdPartyDefinitionItem(solution, definitionItem, cancellationToken); definitions.AddIfNotNull(thirdPartyItem); } definitions.Add(definitionItem); return definitions.ToImmutable(); } public static bool TryGoToDefinition( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { var definitions = GetDefinitions(symbol, solution, thirdPartyNavigationAllowed, cancellationToken); var title = string.Format(EditorFeaturesResources._0_declarations, FindUsagesHelpers.GetDisplayName(symbol)); return threadingContext.JoinableTaskFactory.Run( () => streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, cancellationToken)); } public static bool TryGoToDefinition( ImmutableArray<DefinitionItem> definitions, Solution solution, string title, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken) { return threadingContext.JoinableTaskFactory.Run(() => streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, cancellationToken)); } } }
1