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: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</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: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</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: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</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: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</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|]<int>();
}
}";
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|]<int>();
}
}";
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|]<int> 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|]<int>();
}
}";
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|]<int>();
}
}";
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|]<int> 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|]<int>();
}
}";
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|]<int>();
}
}";
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|]<int> 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|]<int>();
}
}";
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|]<int>();
}
}";
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|]<int> 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.
$ PE L [L ! ~# @ @ @ ,# O @ ` H .text `.rsrc @ @ @.reloc `
@ B `# H t
*(
*(
*(
*(
* BSJB v4.0.30319 l @ #~ #Strings d #US l #GUID | < |